C#字符串的几种常用方法

开发 后端
我们将为大家极少C#字符串的几种常用方法,包括使用StringBuilder、string关键字与StringBuilder类和其他字符串使用。

C#字符串常用方法

一、string关键字与StringBuilder类

C#字符串是使用string关键字声明的一个字符数组。字符串是使用引号声明的,如下例所示:

strings="Hello,World!";

字符串对象是“不可变的”,即它们一旦创建就无法更改。对字符串进行操作的方法实际上返回的是新的字符串对象。因此,出于性能方面的原因,大量的连接或其他涉及字符串的操作应当用StringBuilder类执行,如下所示:

  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、转义字符“\”

字符串中可以包含转义符,如“\n”(新行)和“\t”(制表符)。

如果希望包含反斜杠,则它前面必须还有另一个反斜杠,如“\\”。

2、“@”符号

@符号会告知字符串构造函数忽略转义符和分行符。

因此,以下两个字符串是完全相同的:

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

3、ToString()

如同所有从Object派生的对象一样,字符串也提供了ToString方法,用于将值转换为字符串。此方法可用于将数值转换为C#字符串,如下所示:

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

另外,可以通过参数格式化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":为月份数值转换的字符串;
  4. //"HH":表示24小时制的小时;"hh"表示12小时制的小时;

4、SubString()

格式:Substring(intstartindex,intlen)

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

参数Startindex索引从0开始,且最大值必须小于源字符串的长度,否则会编译异常;

参数len的值必须不大于源字符串索引指定位置开始,之后的字符串字符总长度,否则会出现异常;

示例:

  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()

将字符串拆分为子字符串(如将句子拆分为各个单词)是一个常见的编程任务。Split()方法使用分隔符(如空格字符)char数组,并返回一个子字符串数组。您可以使用foreach访问此数组。

示例:

  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方法分析字符串。此方法返回一个字符串数组,其中每个元素是一个单词。作为输入,Split采用一个字符数组指示哪些字符被用作分隔符。本示例中使用了空格、逗号、句点、冒号和制表符。一个含有这些分隔符的数组被传递给Split,并使用结果字符串数组分别显示句子中的每个单词。

示例:

  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对象移除所有前导空白字符和尾部空白字符。

示例:

  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)

用于将字符复制到字符数组。

示例:

  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. }

示例:修改字符串内容

字符串是不可变的,因此不能修改字符串的内容。但是,可以将字符串的内容提取到非不可变的窗体中,并对其进行修改,以形成新的字符串实例。

下面的示例使用ToCharArray方法来将字符串的内容提取到char类型的数组中。然后修改此数组中的某些元素。之后,使用char数组创建新的字符串实例。

  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、比较

比较两个字符串的最简单方法是使用==和!=运算符,执行区分大小写的比较。

  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()方法,它根据某个字符串是否小于(<)或大于(>)另一个,返回一个整数值。比较字符串时使用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;否则,返回它出现的第一个位置的索引(从零开始)。

示例:

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

string类型(它是System.String类的别名)为搜索字符串的内容提供了许多有用的方法。下面的示例使用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类创建了一个字符串缓冲区,用于在程序执行大量字符串操作时提供更好的性能。StringBuilder字符串还允许您重新分配个别字符,这些字符是内置字符串数据类型所不支持的。例如,此代码在不创建新字符串的情况下更改了一个字符串的内容:

示例:

  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对象用于从一组数值类型中创建字符串。

示例:

  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#调用ImageAnimator
  3. C#连接Access、SQL Server数据库
  4. 浅谈C#固定的和活动的变量
  5. 介绍C#中的值类型
责任编辑:彭凡 来源: 百度空间
相关推荐

2009-08-07 15:49:46

使用C#字符串

2009-09-14 18:11:23

C#排序方法

2010-11-26 11:20:31

MySQL字符串处理函

2009-09-02 16:21:20

C#字符串

2021-05-18 09:08:18

字符串子串对象

2009-08-07 14:22:56

C#字符串搜索

2009-08-24 17:06:37

C#字符串

2009-08-06 16:01:09

C#字符串函数大全

2009-08-07 14:34:33

C#模式字符串

2009-08-26 13:24:54

C#字符串

2009-08-24 13:04:44

操作步骤C#字符串

2009-08-07 14:15:21

C#字符串分割

2009-08-07 13:50:11

C#字符串

2009-08-07 14:46:59

C#匹配字符串

2020-10-16 18:35:53

JavaScript字符串正则表达式

2009-08-21 15:06:09

C#连接字符串

2009-08-20 17:30:02

C#连接字符串

2009-08-28 10:39:37

C#数值字符串

2009-08-07 15:58:54

C#字符串插入html

2009-09-02 15:53:27

C#判断字符串应用
点赞
收藏

51CTO技术栈公众号