C#字符串String及字符Char的相關(guān)方法
一、字符串:
1、訪問(wèn)String中的字符:
string本身可看作一個(gè)Char數(shù)組。
string s = "hello world"; for (int i = 0; i < s.Length; i++) { Console.WriteLine(s[i]); } //或者 foreach (char c in s) { Console.WriteLine(c); }
打散為字符數(shù)組(ToCharArray)
string s = "Hello World"; char[] arr = s.ToCharArray(); // Console.WriteLine(arr[0]); // 輸出數(shù)組的第一個(gè)元素,輸出"H"
2、截取子串:Substring(startIndex,[length]),包括startIndex處的字符。
string s = "hello world"; Console.WriteLine(s.Substring(3));//lo world Console.WriteLine(s.Substring(3, 4));//lo w
3、查找子串:IndexOf(subString)、LastIndexOf(subString),Contains(subString)
string s = "hello world"; Console.WriteLine(s.IndexOf("o"));//4 Console.WriteLine(s.LastIndexOf("o"));//7 Console.WriteLine(s.IndexOf('l'));//查找該字符串中的第一次'l'出現(xiàn)位置 2 Console.WriteLine(s.IndexOf('l', 4));//查找該字符串中的第四次'l'出現(xiàn)位置 9 Console.WriteLine(s.IndexOf('l', 5, 6)); //從前向后定位從第5位開(kāi)始和再數(shù)6位位置之間'l'出現(xiàn)的位置; 9 Console.WriteLine(s.Contains("e"));//True
4、左右填充子字符串到指定長(zhǎng)度:PadLeft(totalLength,char)、PadRight(totalLength,char)
string s = "hello world"; Console.WriteLine(s.PadLeft(15, '*'));//****hello world Console.WriteLine(s.PadRight(15, '*'));//hello world****
5、轉(zhuǎn)化大小寫:ToUpper()、ToLower()
string s = "Hello World"; Console.WriteLine(s.ToUpper());//HELLO WORLD Console.WriteLine(s.ToLower());//hello world
6、刪除字符串指定位置的字符串片段:Remove(startIndex,length)
string s = "Hello World"; Console.WriteLine(s.Remove(7));//Hello W Console.WriteLine(s.Remove(7,1));//Hello Wrld
7、替換子字符串:Replace(oldStr,newStr)
string s = "Hello World"; Console.WriteLine(s.Replace("l","*"));//He**o Wor*d Console.WriteLine(s.Replace("or","*"));//Hello W*ld
8、去掉首尾空白或指定字符:Trim()、TrimStart()、TrimEnd()
string s = " Hello World "; Console.WriteLine(s.Trim());//"Hello World" Console.WriteLine(s.TrimStart());// "Hello World " Console.WriteLine(s.TrimEnd());// " Hello World" string s1 = "hello Worldhd"; Console.WriteLine(s1.Trim('h','d'));//ello Worl Console.WriteLine(s1.TrimStart('h','d'));//ello Worldhd Console.WriteLine(s1.TrimEnd('h','d'));//hello Worl
9、在index前位置插入字符:Insert(index,str)
string s = "Hello World"; Console.WriteLine(s.Insert(6,"測(cè)試"));//Hello 測(cè)試World
10、將字符串按某個(gè)特殊字符(串)進(jìn)行分割,返回字符串?dāng)?shù)組:Split(char/char[]/string[],[StringSplitOptions]
string s = "Hello Wor ld "; Console.WriteLine(s.Split('o'));//"Hell","W", "r ld " Console.WriteLine(s.Split('e', 'd'));// "H","llo Wor l"," " Console.WriteLine(s.Split(new string[] { " " }, StringSplitOptions.None));//"Hello","Wor","","ld"," " Console.WriteLine(s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries));//"Hello","Wor","ld" foreach (string sub in s.Split('o')) { Console.WriteLine(sub); }
11、字符串合并
1、String.Concat(str1, str2, …., strn):將n個(gè)字符串連接,中間沒(méi)有連接符。字符串連接也可以用 ‘+’ 來(lái)實(shí)現(xiàn)。
2、將字符串列表(string[],IEnumerable<string>)用str將各項(xiàng)串連起來(lái),靜態(tài)函數(shù)Join(SplitCh, array)
string[] arr = {"Hello”,” World"}; Console.WriteLine(string.Join("*", arr));//Hello*World
3、實(shí)例方法StringBuilder.Append
StringBuilder sb =new StringBuilder(); // 聲明一個(gè)字符串構(gòu)造器實(shí)例 sb.Append("A"); // 使用字符串構(gòu)造器連接字符串能獲得更高的性能 sb.Append('B'); Console.WriteLine(sb.ToString());// 輸出"AB"
12、格式化,靜態(tài)函數(shù)Format(占位符,變量)
string s = "Hello World"; Console.WriteLine(string.Format("I Love \"{0}\"", s));//I Love "Hello World" Console.WriteLine(string.Format("{0:C}", 120.2));//¥120.20 Console.WriteLine(string.Format("{0:yyyy年MM月dd日}", DateTime.Now));
13、與數(shù)字的轉(zhuǎn)換:
1、Int32.TryParse(string,out bool ):始終不拋異常,返回true/false來(lái)說(shuō)明是否成功解析。string為null返回解析不成功。
int ret = 0; if (int.TryParse("120.5", out ret))//轉(zhuǎn)換異常! { Console.WriteLine(ret); } else { Console.WriteLine("轉(zhuǎn)換異常!"); }
2、Int32.Parse(string):解析不成功會(huì)拋出異常。string為null時(shí)拋出“值不能為 null。參數(shù)名: String”異常。
try { Console.WriteLine(int.Parse("120.5"));//輸入字符串的格式不正確 } catch (Exception e) { Console.WriteLine(e.Message); }
3、Convert.ToInt32(string):解析不成功會(huì)拋出異常,但是string為null時(shí)不拋異常返回0.
try { Console.WriteLine(Convert.ToInt32("120.5"));//輸入字符串的格式不正確。 } catch (Exception e) { Console.WriteLine(e.Message); }
14、字符串的比較:
1、Compare()是CompareTo()的靜態(tài)版本,返回小于,大于還是等于后者字符串(分別為-1,1,0)
string str1 = "you are very happy!!"; string str2 = "I am very happy!!"; Console.WriteLine( string.Compare(str1, str2));//1 Console.WriteLine(str1.CompareTo(str2));//1
2、CompareOrdinal():對(duì)兩字符串比較,而不考慮本地化語(yǔ)言和文化。將整個(gè)字符串每5個(gè)字符(10個(gè)字節(jié))分成一組,然后逐個(gè)比較,找到第一個(gè)不相同的ASCII碼后退出循環(huán)。并且求出兩者的ASCII碼的差。
string str1 = "you are very happy!!"; string str2 = "I am very happy!!"; Console.WriteLine(string.CompareOrdinal(str1, str2));//48
3、Equals()與“==”等價(jià),靜態(tài)或?qū)嵗鼸quals,返回相等還是不等(true/false).
string str2 = "I am very happy!!"; string str3 = "I am very happy!!"; Console.WriteLine(str2.Equals(str3));//True Console.WriteLine(str2 == str3);//True
15、字符串的復(fù)制
(1)、String.Copy(str):參數(shù)str為要復(fù)制的字符串,它回返回一個(gè)與該字符串相等的字符串
(2)、SreStr.CopyTo(StartOfSreStr, DestStr, StartOfDestStr, CopyLen):它必須被要復(fù)制的字符串實(shí)例調(diào)用,它可以實(shí)現(xiàn)復(fù)制其中某一部分到目標(biāo)字符串的指定位置
string s = "Hello World"; string s1 = String.Copy(s); Console.WriteLine(s1);//Hello World char[] s2 = new char[20]; s.CopyTo(2, s2, 0, 8); Console.WriteLine(s2);//llo Worl000000000000000000000000
16、判斷是否是已某種字符串開(kāi)始或者結(jié)束
string s = "Hello World"; Console.WriteLine(s.StartsWith("He")); // True Console.WriteLine(s.EndsWith("He")); // False
17、判斷字符是否為null或者為空,返回值為bool;
string s = "Hello World"; string s2 = null; Console.WriteLine(string.IsNullOrEmpty(s)); // False Console.WriteLine(string.IsNullOrEmpty(s2)); // True
二、char字符。
1、Char的表示方法:
- 字面法:char a=’x’
- 十六進(jìn)制法:char a=’\x0058’
- 顯示轉(zhuǎn)換整數(shù):char a=(char)88
- Unicode形式:char a=’\u0058’
2、轉(zhuǎn)義字符:
- \n =\u000a 換行符
- \t =\u0009 制表符
- \r =\u000d 回車符
- \“ =\u0022 雙引號(hào)
- \' =\u0027 單引號(hào)
- \\ =\u005c 反斜杠
- \b =\u0008 退格符
3、char的靜態(tài)方法:
- char.IsDigit():是否為十進(jìn)制數(shù)字
- char.IsNumber():數(shù)字
- char.IsLetter():字母
- char.IsLetterOrdigt():字母或數(shù)組
- char.IsUpper()/IsLower():大小寫字母
- char.IsPunctuation():標(biāo)點(diǎn)符號(hào)
- char.IsSymbol():符號(hào)字符
- char.IsControl():控制字符
- char.IsSeprator():分隔符
- char.IsWhiteSpace():空白字符
- char.GetNumberialValue():獲取數(shù)字值
- char.ToUpper()/ToLower():更改大小寫
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用Enum.TryParse()實(shí)現(xiàn)枚舉安全轉(zhuǎn)換
這篇文章介紹了C#使用Enum.TryParse()實(shí)現(xiàn)枚舉安全轉(zhuǎn)換的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08Revit API取得變量的內(nèi)參名稱實(shí)例代碼
這篇文章介紹了Revit API取得變量的內(nèi)參名稱實(shí)例代碼,有需要的朋友可以參考一下2013-11-11C#實(shí)現(xiàn)基于任務(wù)的異步編程模式
本文詳細(xì)講解了C#實(shí)現(xiàn)基于任務(wù)的異步編程模式,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04C# 4.0 大數(shù)的運(yùn)算--BigInteger的應(yīng)用詳解
本篇文章是對(duì)C# 4.0 大數(shù)的運(yùn)算 BigInteger的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05