C#字符串的幾種常用方法
C#字符串常用方法
一、string關(guān)鍵字與StringBuilder類(lèi)
C#字符串是使用string關(guān)鍵字聲明的一個(gè)字符數(shù)組。字符串是使用引號(hào)聲明的,如下例所示:
strings="Hello,World!";
字符串對(duì)象是“不可變的”,即它們一旦創(chuàng)建就無(wú)法更改。對(duì)字符串進(jìn)行操作的方法實(shí)際上返回的是新的字符串對(duì)象。因此,出于性能方面的原因,大量的連接或其他涉及字符串的操作應(yīng)當(dāng)用StringBuilder類(lèi)執(zhí)行,如下所示:
- System.Text.StringBuildersb=newSystem.Text.StringBuilder();
 - sb.Append("one");
 - sb.Append("two");
 - sb.Append("three");
 - stringstr=sb.ToString();
 
二、C#字符串使用
1、轉(zhuǎn)義字符“\”
字符串中可以包含轉(zhuǎn)義符,如“\n”(新行)和“\t”(制表符)。
如果希望包含反斜杠,則它前面必須還有另一個(gè)反斜杠,如“\\”。
2、“@”符號(hào)
@符號(hào)會(huì)告知字符串構(gòu)造函數(shù)忽略轉(zhuǎn)義符和分行符。
因此,以下兩個(gè)字符串是完全相同的:
- stringp1="\\\\MyDocuments\\MyFiles\\";
 - stringp2=@"\\MyDocuments\MyFiles\";
 
3、ToString()
如同所有從Object派生的對(duì)象一樣,字符串也提供了ToString方法,用于將值轉(zhuǎn)換為字符串。此方法可用于將數(shù)值轉(zhuǎn)換為C#字符串,如下所示:
- intyear=1999;
 - stringmsg="Evewasbornin"+year.ToString();
 - System.Console.WriteLine(msg);//outputs"Evewasbornin1999"
 
另外,可以通過(guò)參數(shù)格式化ToString()的顯示輸出。如,對(duì)于時(shí)間類(lèi)型格式,可以通過(guò)ToString()方法自定義時(shí)間顯示格式。如:
- System.DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff");
 - //outputs"2009-03-1118:05:16.345"
 - //"MM":指定月份為2位字符串,不足2位則前方補(bǔ)"0";"M":為月份數(shù)值轉(zhuǎn)換的字符串;
 - //"HH":表示24小時(shí)制的小時(shí);"hh"表示12小時(shí)制的小時(shí);
 
4、SubString()
格式:Substring(intstartindex,intlen)
用于獲取源字符串指定起始位置startindex,指定長(zhǎng)度len的字符串。
參數(shù)Startindex索引從0開(kāi)始,且最大值必須小于源字符串的長(zhǎng)度,否則會(huì)編譯異常;
參數(shù)len的值必須不大于源字符串索引指定位置開(kāi)始,之后的字符串字符總長(zhǎng)度,否則會(huì)出現(xiàn)異常;
示例:
- strings4="VisualC#Express";
 - System.Console.WriteLine(s4.Substring(7,2));//outputs"C#"
 - System.Console.WriteLine(s4.Replace("C#","Basic"));//outputs"VisualBasicExpress"
 
5、Replace()
格式:Replace(stringoldValue,stringnewValue)
用于C#字符串中特定字符串組合的替換,即將源字符串中的所有oldValue字符串替換為newValue字符串。
示例:
- strings5="VisualC#Express";
 - System.Console.WriteLine(s5.Replace("C#","VB"));//outputs"VisualVBExpress"
 
6、Split()
將字符串拆分為子字符串(如將句子拆分為各個(gè)單詞)是一個(gè)常見(jiàn)的編程任務(wù)。Split()方法使用分隔符(如空格字符)char數(shù)組,并返回一個(gè)子字符串?dāng)?shù)組。您可以使用foreach訪問(wèn)此數(shù)組。
示例:
- char[]delimit=newchar[]{''};
 - strings14="Thecatsatonthemat.";
 - foreach(stringsubstrins14.Split(delimit))
 - {
 - System.Console.WriteLine(substr);
 - }
 
此代碼將在單獨(dú)的行上輸出每個(gè)單詞,如下所示:
The
cat
sat
on
the
mat.
下面的代碼示例演示如何使用System.String.Split方法分析字符串。此方法返回一個(gè)字符串?dāng)?shù)組,其中每個(gè)元素是一個(gè)單詞。作為輸入,Split采用一個(gè)字符數(shù)組指示哪些字符被用作分隔符。本示例中使用了空格、逗號(hào)、句點(diǎn)、冒號(hào)和制表符。一個(gè)含有這些分隔符的數(shù)組被傳遞給Split,并使用結(jié)果字符串?dāng)?shù)組分別顯示句子中的每個(gè)單詞。
示例:
- classTestStringSplit
 - {
 - staticvoidMain()
 - {
 - char[]delimiterChars={'',',','.',':','\t'};
 - stringtext="one\ttwothree:four,fivesixseven";
 - System.Console.WriteLine("Originaltext:'{0}'",text);
 - string[]words=text.Split(delimiterChars);
 - System.Console.WriteLine("{0}wordsintext:",words.Length);
 - foreach(stringsinwords)
 - {
 - System.Console.WriteLine(s);
 - }
 - }
 - }
 
輸出:
Originaltext:'onetwothree:four,fivesixseven'
7wordsintext:
one
two
three
four
five
six
seven
另外,還可通過(guò)正則表達(dá)式Regex.Split()的方法,通過(guò)C#字符串分隔字符串。
示例:
- usingSystem.Text.RegularExpressions;//需要引用正則表達(dá)式的命名空間
 - stringstr="aaajsbbbjsccc";
 - string[]sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);//正則表達(dá)式
 - //RegexOptions.IgnoreCase表示忽略字母大小寫(xiě)
 - foreach(stringiinsArray)Response.Write(i.ToString()+"
 "
);
輸出:
aaa
bbb
ccc
7、Trim()
Trim()從當(dāng)前String對(duì)象移除所有前導(dǎo)空白字符和尾部空白字符。
示例:
- strings7="VisualC#Express";
 - System.Console.WriteLine(s7);//outputs"VisualC#Express"
 - System.Console.WriteLine(s7.Trim());//outputs"VisualC#Express"
 
8、ToCharArray()
格式:ToCharArray(intstartindex,intlen)
用于將字符復(fù)制到字符數(shù)組。
示例:
- strings8="Hello,World";
 - char[]arr=s8.ToCharArray(0,s8.Length);
 - foreach(charcinarr)
 - {
 - System.Console.Write(c);//outputs"Hello,World"
 - }
 
示例:修改字符串內(nèi)容
字符串是不可變的,因此不能修改字符串的內(nèi)容。但是,可以將字符串的內(nèi)容提取到非不可變的窗體中,并對(duì)其進(jìn)行修改,以形成新的字符串實(shí)例。
下面的示例使用ToCharArray方法來(lái)將字符串的內(nèi)容提取到char類(lèi)型的數(shù)組中。然后修改此數(shù)組中的某些元素。之后,使用char數(shù)組創(chuàng)建新的字符串實(shí)例。
- classModifyStrings
 - {
 - staticvoidMain()
 - {
 - stringstr="Thequickbrownfoxjumpedoverthefence";
 - System.Console.WriteLine(str);
 - char[]chars=str.ToCharArray();
 - intanimalIndex=str.IndexOf("fox");
 - if(animalIndex!=-1)
 - {
 - chars[animalIndex++]='c';
 - chars[animalIndex++]='a';
 - chars[animalIndex]='t';
 - }
 - stringstr2=newstring(chars);
 - System.Console.WriteLine(str2);
 - }
 - }
 
輸出:
Thequickbrownfoxjumpedoverthefence
Thequickbrowncatjumpedoverthefence
9、利用索引訪問(wèn)字符串中的各個(gè)字符
格式:str[intindex]
示例:逆序排列字符串
- strings9="Printingbackwards";
 - for(inti=0;i
 - {
 - System.Console.Write(s9[s9.Length-i-1]);//outputs"sdrawkcabgnitnirP"
 - }
 
10、更改大小寫(xiě),ToUpper()和ToLower()
若要將字符串中的字母更改為大寫(xiě)或小寫(xiě),可以使用ToUpper()或ToLower()。如下所示:
- strings10="BattleofHastings,1066";
 - System.Console.WriteLine(s10.ToUpper());//outputs"BATTLEOFHASTINGS1066"
 - System.Console.WriteLine(s10.ToLower());//outputs"battleofhastings1066"
 
11、比較
比較兩個(gè)字符串的最簡(jiǎn)單方法是使用==和!=運(yùn)算符,執(zhí)行區(qū)分大小寫(xiě)的比較。
- stringcolor1="red";
 - stringcolor2="green";
 - stringcolor3="red";
 - if(color1==color3)
 - {
 - System.Console.WriteLine("Equal");
 - }
 - if(color1!=color2)
 - {
 - System.Console.WriteLine("Notequal");
 - }
 
12、CompareTo()
字符串對(duì)象也有一個(gè)CompareTo()方法,它根據(jù)某個(gè)字符串是否小于(<)或大于(>)另一個(gè),返回一個(gè)整數(shù)值。比較字符串時(shí)使用Unicode值,小寫(xiě)的值小于大寫(xiě)的值。
示例:
- strings121="ABC";
 - strings122="abc";
 - if(s121.CompareTo(s122)>0)
 - {
 - System.Console.WriteLine("Greater-than");
 - }
 - else
 - {
 - System.Console.WriteLine("Less-than");
 - }
 
13、字符串索引
若要在一個(gè)字符串中搜索另一個(gè)字符串,可以使用IndexOf()。如果未找到搜索字符串,IndexOf()返回-1;否則,返回它出現(xiàn)的第一個(gè)位置的索引(從零開(kāi)始)。
示例:
- strings13="BattleofHastings,1066";
 - System.Console.WriteLine(s13.IndexOf("Hastings"));//outputs10
 - System.Console.WriteLine(s13.IndexOf("1967"));//outputs-1
 
string類(lèi)型(它是System.String類(lèi)的別名)為搜索字符串的內(nèi)容提供了許多有用的方法。下面的示例使用IndexOf、LastIndexOf、StartsWith和EndsWith方法。
示例:
- classStringSearch
 - {
 - staticvoidMain()
 - {
 - stringstr="Asillysentenceusedforsillypurposes.";
 - System.Console.WriteLine("'{0}'",str);
 - booltest1=str.StartsWith("asilly");
 - System.Console.WriteLine("startswith'asilly'?{0}",test1);
 - booltest2=str.StartsWith("asilly",System.StringComparison.OrdinalIgnoreCase);
 - System.Console.WriteLine("startswith'asilly'?{0}(ignoringcase)",test2);
 - booltest3=str.EndsWith(".");
 - System.Console.WriteLine("endswith'.'?{0}",test3);
 - intfirst=str.IndexOf("silly");
 - intlast=str.LastIndexOf("silly");
 - stringstr2=str.Substring(first,last-first);
 - System.Console.WriteLine("betweentwo'silly'words:'{0}'",str2);
 - }
 - }
 
輸出:
'Asillysentenceusedforsillypurposes.'
startswith'asilly'?False
startswith'asilly'?True(ignorecase)
endswith'.'?True
betweentwo'silly'words:'sillysentenceusedfor'
三、使用StringBuilder
StringBuilder類(lèi)創(chuàng)建了一個(gè)字符串緩沖區(qū),用于在程序執(zhí)行大量字符串操作時(shí)提供更好的性能。StringBuilder字符串還允許您重新分配個(gè)別字符,這些字符是內(nèi)置字符串?dāng)?shù)據(jù)類(lèi)型所不支持的。例如,此代碼在不創(chuàng)建新字符串的情況下更改了一個(gè)字符串的內(nèi)容:
示例:
- System.Text.StringBuildersb=newSystem.Text.StringBuilder("Rat:theidealpet");
 - sb[0]='C';
 - System.Console.WriteLine(sb.ToString());//displaysCat:theidealpet
 - System.Console.ReadLine();
 
在以下示例中,StringBuilder對(duì)象用于從一組數(shù)值類(lèi)型中創(chuàng)建字符串。
示例:
- classTestStringBuilder
 - {
 - staticvoidMain()
 - {
 - System.Text.StringBuildersb=newSystem.Text.StringBuilder();
 - //Createastringcomposedofnumbers0-9
 - for(inti=0;i<10;i++)
 - {
 - sb.Append(i.ToString());
 - }
 - System.Console.WriteLine(sb);//displays0123456789
 - //Copyonecharacterofthestring(notpossiblewithaSystem.String)
 - sb[0]=sb[9];
 - System.Console.WriteLine(sb);//displays9123456789
 - }
 - }
 
【編輯推薦】















 
 
 
 
 
 
 