自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#字符串的幾種常用方法

開發(fā) 后端
我們將為大家極少C#字符串的幾種常用方法,包括使用StringBuilder、string關(guān)鍵字與StringBuilder類和其他字符串使用。

C#字符串常用方法

一、string關(guān)鍵字與StringBuilder類

C#字符串是使用string關(guān)鍵字聲明的一個字符數(shù)組。字符串是使用引號聲明的,如下例所示:

strings="Hello,World!";

字符串對象是“不可變的”,即它們一旦創(chuàng)建就無法更改。對字符串進行操作的方法實際上返回的是新的字符串對象。因此,出于性能方面的原因,大量的連接或其他涉及字符串的操作應(yīng)當用StringBuilder類執(zhí)行,如下所示:

  1. System.Text.StringBuildersb=newSystem.Text.StringBuilder();
  2. sb.Append("one");
  3. sb.Append("two");
  4. sb.Append("three");
  5. stringstr=sb.ToString();

二、C#字符串使用

1、轉(zhuǎn)義字符“\”

字符串中可以包含轉(zhuǎn)義符,如“\n”(新行)和“\t”(制表符)。

如果希望包含反斜杠,則它前面必須還有另一個反斜杠,如“\\”。

2、“@”符號

@符號會告知字符串構(gòu)造函數(shù)忽略轉(zhuǎn)義符和分行符。

因此,以下兩個字符串是完全相同的:

  1. stringp1="\\\\MyDocuments\\MyFiles\\";
  2. stringp2=@"\\MyDocuments\MyFiles\";

3、ToString()

如同所有從Object派生的對象一樣,字符串也提供了ToString方法,用于將值轉(zhuǎn)換為字符串。此方法可用于將數(shù)值轉(zhuǎn)換為C#字符串,如下所示:

  1. intyear=1999;
  2. stringmsg="Evewasbornin"+year.ToString();
  3. System.Console.WriteLine(msg);//outputs"Evewasbornin1999"

另外,可以通過參數(shù)格式化ToString()的顯示輸出。如,對于時間類型格式,可以通過ToString()方法自定義時間顯示格式。如:

  1. System.DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff");
  2. //outputs"2009-03-1118:05:16.345"
  3. //"MM":指定月份為2位字符串,不足2位則前方補"0";"M":為月份數(shù)值轉(zhuǎn)換的字符串;
  4. //"HH":表示24小時制的小時;"hh"表示12小時制的小時;

4、SubString()

格式:Substring(intstartindex,intlen)

用于獲取源字符串指定起始位置startindex,指定長度len的字符串。

參數(shù)Startindex索引從0開始,且最大值必須小于源字符串的長度,否則會編譯異常;

參數(shù)len的值必須不大于源字符串索引指定位置開始,之后的字符串字符總長度,否則會出現(xiàn)異常;

示例:

  1. strings4="VisualC#Express";
  2. System.Console.WriteLine(s4.Substring(7,2));//outputs"C#"
  3. System.Console.WriteLine(s4.Replace("C#","Basic"));//outputs"VisualBasicExpress"

5、Replace()

格式:Replace(stringoldValue,stringnewValue)

用于C#字符串中特定字符串組合的替換,即將源字符串中的所有oldValue字符串替換為newValue字符串。

示例:

  1. strings5="VisualC#Express";
  2. System.Console.WriteLine(s5.Replace("C#","VB"));//outputs"VisualVBExpress"

6、Split()

將字符串拆分為子字符串(如將句子拆分為各個單詞)是一個常見的編程任務(wù)。Split()方法使用分隔符(如空格字符)char數(shù)組,并返回一個子字符串數(shù)組。您可以使用foreach訪問此數(shù)組。

示例:

  1. char[]delimit=newchar[]{''};
  2. strings14="Thecatsatonthemat.";
  3. foreach(stringsubstrins14.Split(delimit))
  4. {
  5. System.Console.WriteLine(substr);
  6. }

此代碼將在單獨的行上輸出每個單詞,如下所示:

The

cat

sat

on

the

mat.

下面的代碼示例演示如何使用System.String.Split方法分析字符串。此方法返回一個字符串數(shù)組,其中每個元素是一個單詞。作為輸入,Split采用一個字符數(shù)組指示哪些字符被用作分隔符。本示例中使用了空格、逗號、句點、冒號和制表符。一個含有這些分隔符的數(shù)組被傳遞給Split,并使用結(jié)果字符串數(shù)組分別顯示句子中的每個單詞。

示例:

  1. classTestStringSplit
  2. {
  3. staticvoidMain()
  4. {
  5. char[]delimiterChars={'',',','.',':','\t'};
  6. stringtext="one\ttwothree:four,fivesixseven";
  7. System.Console.WriteLine("Originaltext:'{0}'",text);
  8. string[]words=text.Split(delimiterChars);
  9. System.Console.WriteLine("{0}wordsintext:",words.Length);
  10. foreach(stringsinwords)
  11. {
  12. System.Console.WriteLine(s);
  13. }
  14. }
  15. }

輸出:

Originaltext:'onetwothree:four,fivesixseven'

7wordsintext:

one

two

three

four

five

six

seven

另外,還可通過正則表達式Regex.Split()的方法,通過C#字符串分隔字符串。

示例:

  1. usingSystem.Text.RegularExpressions;//需要引用正則表達式的命名空間
  2. stringstr="aaajsbbbjsccc";
  3. string[]sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);//正則表達式
  4. //RegexOptions.IgnoreCase表示忽略字母大小寫
  5. foreach(stringiinsArray)Response.Write(i.ToString()+"

    ");

輸出:

aaa

bbb

ccc

7、Trim()

Trim()從當前String對象移除所有前導(dǎo)空白字符和尾部空白字符。

示例:

  1. strings7="VisualC#Express";
  2. System.Console.WriteLine(s7);//outputs"VisualC#Express"
  3. System.Console.WriteLine(s7.Trim());//outputs"VisualC#Express"

8、ToCharArray()

格式:ToCharArray(intstartindex,intlen)

用于將字符復(fù)制到字符數(shù)組。

示例:

  1. strings8="Hello,World";
  2. char[]arr=s8.ToCharArray(0,s8.Length);
  3. foreach(charcinarr)
  4. {
  5. System.Console.Write(c);//outputs"Hello,World"
  6. }

示例:修改字符串內(nèi)容

字符串是不可變的,因此不能修改字符串的內(nèi)容。但是,可以將字符串的內(nèi)容提取到非不可變的窗體中,并對其進行修改,以形成新的字符串實例。

下面的示例使用ToCharArray方法來將字符串的內(nèi)容提取到char類型的數(shù)組中。然后修改此數(shù)組中的某些元素。之后,使用char數(shù)組創(chuàng)建新的字符串實例。

  1. classModifyStrings
  2. {
  3. staticvoidMain()
  4. {
  5. stringstr="Thequickbrownfoxjumpedoverthefence";
  6. System.Console.WriteLine(str);
  7. char[]chars=str.ToCharArray();
  8. intanimalIndex=str.IndexOf("fox");
  9. if(animalIndex!=-1)
  10. {
  11. chars[animalIndex++]='c';
  12. chars[animalIndex++]='a';
  13. chars[animalIndex]='t';
  14. }
  15. stringstr2=newstring(chars);
  16. System.Console.WriteLine(str2);
  17. }
  18. }

輸出:

Thequickbrownfoxjumpedoverthefence

Thequickbrowncatjumpedoverthefence

9、利用索引訪問字符串中的各個字符

格式:str[intindex]

示例:逆序排列字符串

  1. strings9="Printingbackwards";
  2. for(inti=0;i
  3. {
  4. System.Console.Write(s9[s9.Length-i-1]);//outputs"sdrawkcabgnitnirP"
  5. }

10、更改大小寫,ToUpper()和ToLower()

若要將字符串中的字母更改為大寫或小寫,可以使用ToUpper()或ToLower()。如下所示:

  1. strings10="BattleofHastings,1066";
  2. System.Console.WriteLine(s10.ToUpper());//outputs"BATTLEOFHASTINGS1066"
  3. System.Console.WriteLine(s10.ToLower());//outputs"battleofhastings1066"

11、比較

比較兩個字符串的最簡單方法是使用==和!=運算符,執(zhí)行區(qū)分大小寫的比較。

  1. stringcolor1="red";
  2. stringcolor2="green";
  3. stringcolor3="red";
  4. if(color1==color3)
  5. {
  6. System.Console.WriteLine("Equal");
  7. }
  8. if(color1!=color2)
  9. {
  10. System.Console.WriteLine("Notequal");
  11. }

12、CompareTo()

字符串對象也有一個CompareTo()方法,它根據(jù)某個字符串是否小于(<)或大于(>)另一個,返回一個整數(shù)值。比較字符串時使用Unicode值,小寫的值小于大寫的值。

示例:

  1. strings121="ABC";
  2. strings122="abc";
  3. if(s121.CompareTo(s122)>0)
  4. {
  5. System.Console.WriteLine("Greater-than");
  6. }
  7. else
  8. {
  9. System.Console.WriteLine("Less-than");
  10. }

13、字符串索引

若要在一個字符串中搜索另一個字符串,可以使用IndexOf()。如果未找到搜索字符串,IndexOf()返回-1;否則,返回它出現(xiàn)的第一個位置的索引(從零開始)。

示例:

  1. strings13="BattleofHastings,1066";
  2. System.Console.WriteLine(s13.IndexOf("Hastings"));//outputs10
  3. System.Console.WriteLine(s13.IndexOf("1967"));//outputs-1

string類型(它是System.String類的別名)為搜索字符串的內(nèi)容提供了許多有用的方法。下面的示例使用IndexOf、LastIndexOf、StartsWith和EndsWith方法。

示例:

  1. classStringSearch
  2. {
  3. staticvoidMain()
  4. {
  5. stringstr="Asillysentenceusedforsillypurposes.";
  6. System.Console.WriteLine("'{0}'",str);
  7. booltest1=str.StartsWith("asilly");
  8. System.Console.WriteLine("startswith'asilly'?{0}",test1);
  9. booltest2=str.StartsWith("asilly",System.StringComparison.OrdinalIgnoreCase);
  10. System.Console.WriteLine("startswith'asilly'?{0}(ignoringcase)",test2);
  11. booltest3=str.EndsWith(".");
  12. System.Console.WriteLine("endswith'.'?{0}",test3);
  13. intfirst=str.IndexOf("silly");
  14. intlast=str.LastIndexOf("silly");
  15. stringstr2=str.Substring(first,last-first);
  16. System.Console.WriteLine("betweentwo'silly'words:'{0}'",str2);
  17. }
  18. }

輸出:

'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)容:

示例:

  1. System.Text.StringBuildersb=newSystem.Text.StringBuilder("Rat:theidealpet");
  2. sb[0]='C';
  3. System.Console.WriteLine(sb.ToString());//displaysCat:theidealpet
  4. System.Console.ReadLine();

在以下示例中,StringBuilder對象用于從一組數(shù)值類型中創(chuàng)建字符串。

示例:

  1. classTestStringBuilder
  2. {
  3. staticvoidMain()
  4. {
  5. System.Text.StringBuildersb=newSystem.Text.StringBuilder();
  6. //Createastringcomposedofnumbers0-9
  7. for(inti=0;i<10;i++)
  8. {
  9. sb.Append(i.ToString());
  10. }
  11. System.Console.WriteLine(sb);//displays0123456789
  12. //Copyonecharacterofthestring(notpossiblewithaSystem.String)
  13. sb[0]=sb[9];
  14. System.Console.WriteLine(sb);//displays9123456789
  15. }
  16. }

【編輯推薦】

  1. 分析C#不安全代碼
  2. 淺析C#調(diào)用ImageAnimator
  3. C#連接Access、SQL Server數(shù)據(jù)庫
  4. 淺談C#固定的和活動的變量
  5. 介紹C#中的值類型
責(zé)任編輯:彭凡 來源: 百度空間
相關(guān)推薦

2009-08-07 15:49:46

使用C#字符串

2009-09-14 18:11:23

C#排序方法

2010-11-26 11:20:31

MySQL字符串處理函

2021-05-18 09:08:18

字符串子串對象

2024-12-23 07:38:20

2009-09-02 16:21:20

C#字符串

2009-08-07 14:46:59

C#匹配字符串

2009-08-26 13:24:54

C#字符串

2009-08-24 17:06:37

C#字符串

2009-08-07 14:15:21

C#字符串分割

2009-08-07 14:22:56

C#字符串搜索

2009-08-07 14:34:33

C#模式字符串

2009-08-24 13:04:44

操作步驟C#字符串

2009-08-07 13:50:11

C#字符串

2009-08-06 16:01:09

C#字符串函數(shù)大全

2009-08-21 15:06:09

C#連接字符串

2020-10-16 18:35:53

JavaScript字符串正則表達式

2009-08-20 17:30:02

C#連接字符串

2009-08-28 10:39:37

C#數(shù)值字符串

2009-08-07 15:58:54

C#字符串插入html
點贊
收藏

51CTO技術(shù)棧公眾號