您的位置:首页 > 编程语言 > C#

C#中String类常用的方法

2012-08-21 11:24 330 查看
C#字符串常用方法

一、string关键字与StringBuilder类

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

strings="Hello,World!";

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

System.Text.StringBuildersb=newSystem.Text.StringBuilder();
sb.Append("one");
sb.Append("two");
sb.Append("three");
stringstr=sb.ToString();


二、C#字符串使用

1、转义字符“\”

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

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

2、“@”符号

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

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

stringp1="\\\\MyDocuments\\MyFiles\\";
stringp2=@"\\MyDocuments\MyFiles\";

3、ToString()

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

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

另外,可以通过参数格式化ToString()的显示输出。如,对于时间类型格式,可以通过ToString()方法自定义时间显示格式。如:

System.DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff");
//outputs"2009-03-1118:05:16.345"
//"MM":指定月份为2位字符串,不足2位则前方补"0";"M":为月份数值转换的字符串;
//"HH":表示24小时制的小时;"hh"表示12小时制的小时;

4、SubString()

格式:Substring(intstartindex,intlen)

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

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

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

示例:

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

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

示例:

char[]delimit=newchar[]{''};
strings14="Thecatsatonthemat.";
foreach(stringsubstrins14.Split(delimit))
{
System.Console.WriteLine(substr);
}

此代码将在单独的行上输出每个单词,如下所示:

The

cat

sat

on

the

mat.

下面的代码示例演示如何使用System.String.Split方法分析字符串。此方法返回一个字符串数组,其中每个元素是一个单词。作为输入,Split采用一个字符数组指示哪些字符被用作分隔符。本示例中使用了空格、逗号、句点、冒号和制表符。一个含有这些分隔符的数组被传递给Split,并使用结果字符串数组分别显示句子中的每个单词。

示例:

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

示例:

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

8、ToCharArray()

格式:ToCharArray(intstartindex,intlen)

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

示例:

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

示例:修改字符串内容

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

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

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<S9.LENGTH;I++) SPAN <>
{
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、比较

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

stringcolor1="red";
stringcolor2="green";
stringcolor3="red";
if(color1==color3)
{
System.Console.WriteLine("Equal");
}
if(color1!=color2)
{
System.Console.WriteLine("Notequal");
}

12、CompareTo()

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

示例:

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

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

示例:

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

在以下示例中,StringBuilder对象用于从一组数值类型中创建字符串。

示例:

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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: