C#字符串的幾種常用方法
C#字符串常用方法
一、string關(guān)鍵字與StringBuilder類
C#字符串是使用string關(guān)鍵字聲明的一個字符數(shù)組。字符串是使用引號聲明的,如下例所示:
strings="Hello,World!";
字符串對象是“不可變的”,即它們一旦創(chuàng)建就無法更改。對字符串進行操作的方法實際上返回的是新的字符串對象。因此,出于性能方面的原因,大量的連接或其他涉及字符串的操作應(yīng)當用StringBuilder類執(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”(制表符)。
如果希望包含反斜杠,則它前面必須還有另一個反斜杠,如“\\”。
2、“@”符號
@符號會告知字符串構(gòu)造函數(shù)忽略轉(zhuǎn)義符和分行符。
因此,以下兩個字符串是完全相同的:
- stringp1="\\\\MyDocuments\\MyFiles\\";
- stringp2=@"\\MyDocuments\MyFiles\";
3、ToString()
如同所有從Object派生的對象一樣,字符串也提供了ToString方法,用于將值轉(zhuǎn)換為字符串。此方法可用于將數(shù)值轉(zhuǎn)換為C#字符串,如下所示:
- intyear=1999;
- stringmsg="Evewasbornin"+year.ToString();
- System.Console.WriteLine(msg);//outputs"Evewasbornin1999"
另外,可以通過參數(shù)格式化ToString()的顯示輸出。如,對于時間類型格式,可以通過ToString()方法自定義時間顯示格式。如:
- System.DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff");
- //outputs"2009-03-1118:05:16.345"
- //"MM":指定月份為2位字符串,不足2位則前方補"0";"M":為月份數(shù)值轉(zhuǎn)換的字符串;
- //"HH":表示24小時制的小時;"hh"表示12小時制的小時;
4、SubString()
格式:Substring(intstartindex,intlen)
用于獲取源字符串指定起始位置startindex,指定長度len的字符串。
參數(shù)Startindex索引從0開始,且最大值必須小于源字符串的長度,否則會編譯異常;
參數(shù)len的值必須不大于源字符串索引指定位置開始,之后的字符串字符總長度,否則會出現(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()
將字符串拆分為子字符串(如將句子拆分為各個單詞)是一個常見的編程任務(wù)。Split()方法使用分隔符(如空格字符)char數(shù)組,并返回一個子字符串數(shù)組。您可以使用foreach訪問此數(shù)組。
示例:
- char[]delimit=newchar[]{''};
- strings14="Thecatsatonthemat.";
- foreach(stringsubstrins14.Split(delimit))
- {
- System.Console.WriteLine(substr);
- }
此代碼將在單獨的行上輸出每個單詞,如下所示:
The
cat
sat
on
the
mat.
下面的代碼示例演示如何使用System.String.Split方法分析字符串。此方法返回一個字符串數(shù)組,其中每個元素是一個單詞。作為輸入,Split采用一個字符數(shù)組指示哪些字符被用作分隔符。本示例中使用了空格、逗號、句點、冒號和制表符。一個含有這些分隔符的數(shù)組被傳遞給Split,并使用結(jié)果字符串數(shù)組分別顯示句子中的每個單詞。
示例:
- 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
另外,還可通過正則表達式Regex.Split()的方法,通過C#字符串分隔字符串。
示例:
- usingSystem.Text.RegularExpressions;//需要引用正則表達式的命名空間
- stringstr="aaajsbbbjsccc";
- string[]sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);//正則表達式
- //RegexOptions.IgnoreCase表示忽略字母大小寫
- foreach(stringiinsArray)Response.Write(i.ToString()+"
"
);
輸出:
aaa
bbb
ccc
7、Trim()
Trim()從當前String對象移除所有前導(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)容提取到非不可變的窗體中,并對其進行修改,以形成新的字符串實例。
下面的示例使用ToCharArray方法來將字符串的內(nèi)容提取到char類型的數(shù)組中。然后修改此數(shù)組中的某些元素。之后,使用char數(shù)組創(chuàng)建新的字符串實例。
- 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、利用索引訪問字符串中的各個字符
格式:str[intindex]
示例:逆序排列字符串
- strings9="Printingbackwards";
- for(inti=0;i
- {
- System.Console.Write(s9[s9.Length-i-1]);//outputs"sdrawkcabgnitnirP"
- }
10、更改大小寫,ToUpper()和ToLower()
若要將字符串中的字母更改為大寫或小寫,可以使用ToUpper()或ToLower()。如下所示:
- strings10="BattleofHastings,1066";
- System.Console.WriteLine(s10.ToUpper());//outputs"BATTLEOFHASTINGS1066"
- System.Console.WriteLine(s10.ToLower());//outputs"battleofhastings1066"
11、比較
比較兩個字符串的最簡單方法是使用==和!=運算符,執(zhí)行區(qū)分大小寫的比較。
- stringcolor1="red";
- stringcolor2="green";
- stringcolor3="red";
- if(color1==color3)
- {
- System.Console.WriteLine("Equal");
- }
- if(color1!=color2)
- {
- System.Console.WriteLine("Notequal");
- }
12、CompareTo()
字符串對象也有一個CompareTo()方法,它根據(jù)某個字符串是否小于(<)或大于(>)另一個,返回一個整數(shù)值。比較字符串時使用Unicode值,小寫的值小于大寫的值。
示例:
- strings121="ABC";
- strings122="abc";
- if(s121.CompareTo(s122)>0)
- {
- System.Console.WriteLine("Greater-than");
- }
- else
- {
- System.Console.WriteLine("Less-than");
- }
13、字符串索引
若要在一個字符串中搜索另一個字符串,可以使用IndexOf()。如果未找到搜索字符串,IndexOf()返回-1;否則,返回它出現(xiàn)的第一個位置的索引(從零開始)。
示例:
- strings13="BattleofHastings,1066";
- System.Console.WriteLine(s13.IndexOf("Hastings"));//outputs10
- System.Console.WriteLine(s13.IndexOf("1967"));//outputs-1
string類型(它是System.String類的別名)為搜索字符串的內(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類創(chuàng)建了一個字符串緩沖區(qū),用于在程序執(zhí)行大量字符串操作時提供更好的性能。StringBuilder字符串還允許您重新分配個別字符,這些字符是內(nèi)置字符串數(shù)據(jù)類型所不支持的。例如,此代碼在不創(chuàng)建新字符串的情況下更改了一個字符串的內(nèi)容:
示例:
- System.Text.StringBuildersb=newSystem.Text.StringBuilder("Rat:theidealpet");
- sb[0]='C';
- System.Console.WriteLine(sb.ToString());//displaysCat:theidealpet
- System.Console.ReadLine();
在以下示例中,StringBuilder對象用于從一組數(shù)值類型中創(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
- }
- }
【編輯推薦】