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

C#字符串操作实例

2009-07-27 13:34 323 查看
一、string关键字与StringBuilder类

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

string s = "Hello, World!";

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

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("one ");

sb.Append("two ");

sb.Append("three");

string str = sb.ToString();

二、字符串使用

1、转移字符“/”

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

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

2、“@”符号

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

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

string p1 = "////My Documents//My Files//";

string p2 = @"http://www.cnblogs.com/xianspace/admin/file://my/ Documents/My Files/";

3、ToString()

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

int year = 1999;

string msg = "Eve was born in " + year.ToString();

System.Console.WriteLine(msg); // outputs "Eve was born in 1999"

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

System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

//outputs "2009-03-11 18:05:16.345"

//"MM":指定月份为2位字符串,不足2位则前方补"0";"M":为月份数值转换的字符串;

//"HH":表示24小时制的小时;"hh"表示12小时制的小时;

4、SubString()

格式:Substring(int startindex, int len)

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

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

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

示例:

string s4 = "Visual C# Express";

System.Console.WriteLine(s4.Substring(7, 2)); // outputs "C#" ,C为第八个字符

System.Console.WriteLine(s4.Replace("C#", "Basic")); // outputs "Visual Basic Express"

5、Replace()

格式:Replace(string oldValue, string newValue)

用于字符串中特定字符串组合的替换,即将源字符串中的所有oldValue 字符串替换为 newValue 字符串。

示例:

string s5 = "Visual C# Express";

System.Console.WriteLine(s5.Replace("C#","VB")); // outputs "Visual VB Express"

6、Split()

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

示例:

char[] delimit = new char[] { ' ' };

string s14 = "The cat sat on the mat.";

foreach (string substr in s14.Split(delimit)) //使用空格拆分

{

System.Console.WriteLine(substr);

}

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

The

cat

sat

on

the

mat.

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

示例:

1 class TestStringSplit
2
3 {
4
5 static void Main()
6
7 {
8
9 char[] delimiterChars = { ' ', ',', '.', ':', '/t' };
10
11
12
13 string text = "one/ttwo three:four,five six seven";
14
15 System.Console.WriteLine("Original text: '{0}'", text);
16
17
18
19 string[] words = text.Split(delimiterChars);
20
21 System.Console.WriteLine("{0} words in text:", words.Length);
22
23
24
25 foreach (string s in words)
26
27 {
28
29 System.Console.WriteLine(s);
30
31 }
32
33 }
34
35 }
36
37
38

输出:

Original text: 'one two three:four,five six seven'

7 words in text:

one

two

three

four

five

six

seven

另外,还可通过正则表达式Regex.Split()的方法,通过字符串分隔字符串。

示例:

using System.Text.RegularExpressions; //需要引用正则表达式的命名空间

string str="aaajsbbbjsccc";

string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase); //正则表达式

// RegexOptions.IgnoreCase 表示忽略字母大小写

foreach (string i in sArray) Response.Write(i.ToString() + "<br>");

输出:

aaa

bbb

ccc

7、Trim()

Trim() 从当前 String 对象移除所有前导空白字符和尾部空白字符。

示例:

string s7 = " Visual C# Express ";

System.Console.WriteLine(s7); // outputs " Visual C# Express "

System.Console.WriteLine(s7.Trim()); // outputs "Visual C# Express"

8、ToCharArray()

格式:ToCharArray(int startindex,int len)

用于将字符复制到字符数组。用于修改字符串等

示例:

string s8 = "Hello, World";

char[] arr = s8.ToCharArray(0, s8.Length);

foreach (char c in arr)

{

System.Console.Write(c); // outputs "Hello, World"

}

示例:修改字符串内容

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

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

class ModifyStrings

{

static void Main()

{

string str = "The quick brown fox jumped over the fence";

System.Console.WriteLine(str);

char[] chars = str.ToCharArray();

int animalIndex = str.IndexOf("fox");

if (animalIndex != -1)

{

chars[animalIndex++] = 'c';

chars[animalIndex++] = 'a';

chars[animalIndex] = 't';

}

string str2 = new string(chars);

System.Console.WriteLine(str2);

}

}

输出:

The quick brown fox jumped over the fence

The quick brown cat jumped over the fence

9、利用索引访问字符串中的各个字符

格式:str[int index]

示例:逆序排列字符串

string s9 = "Printing backwards";

for (int i = 0; i < s9.Length; i++)

{

System.Console.Write(s9[s9.Length - i - 1]); // outputs "sdrawkcab gnitnirP"

}

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

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

string s10 = "Battle of Hastings, 1066";

System.Console.WriteLine(s10.ToUpper()); // outputs "BATTLE OF HASTINGS 1066"

System.Console.WriteLine(s10.ToLower()); // outputs "battle of hastings 1066"

11、比较

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

string color1 = "red";

string color2 = "green";

string color3 = "red";

if (color1 == color3)

{

System.Console.WriteLine("Equal");

}

if (color1 != color2)

{

System.Console.WriteLine("Not equal");

}

12、CompareTo()

字符串对象也有一个 CompareTo() 方法,它根据某个字符串是否小于 (<) 或大于 (>) 另一个,返回一个整数值(小于0或大于等于0)。比较字符串时使用 Unicode 值,小写的值小于大写的值。示例:

string s121 = "ABC";

string s122 = "abc";

if (s121.CompareTo(s122) > 0)

{

System.Console.WriteLine("Greater-than");

}

else

{

System.Console.WriteLine("Less-than");

}

13、字符串索引 IndexOf()。

若要在一个字符串中搜索另一个字符串,可以使用 IndexOf()。如果未找到搜索字符串,IndexOf() 返回 -1;否则,返回它出现的第一个位置的索引(从零开始)。

示例:

string s13 = "Battle of Hastings, 1066";

System.Console.WriteLine(s13.IndexOf("Hastings")); // outputs 10 ,注意从0开始数起

System.Console.WriteLine(s13.IndexOf("1967")); // outputs -1

string 类型(它是 System.String 类的别名)为搜索字符串的内容提供了许多有用的方法。下面的示例使用 IndexOf、LastIndexOf、StartsWith 和 EndsWith 方法。

示例:

class StringSearch

{

static void Main()

{

string str = "A silly sentence used for silly purposes.";

System.Console.WriteLine("'{0}'",str); //'A silly sentence used for silly purposes.'

bool test1 = str.StartsWith("a silly");

System.Console.WriteLine("starts with 'a silly'? {0}", test1); //starts with 'a silly'? False

bool test2 = str.StartsWith("a silly", System.StringComparison.OrdinalIgnoreCase);

System.Console.WriteLine("starts with 'a silly'? {0} (ignoring case)", test2); //starts with 'a silly'? True (ignore case)

bool test3 = str.EndsWith(".");

System.Console.WriteLine("ends with '.'? {0}", test3); //ends with '.'? True

int first = str.IndexOf("silly");

int last = str.LastIndexOf("silly");

string str2 = str.Substring(first, last - first);

System.Console.WriteLine("between two 'silly' words: '{0}'", str2); //between two 'silly' words: 'silly sentence used for '

}

}

输出:

'A silly sentence used for silly purposes.'

starts with 'a silly'? False

starts with 'a silly'? True (ignore case)

ends with '.'? True

between two 'silly' words: 'silly sentence used for '

三、使用 StringBuilder

StringBuilder 类创建了一个字符串缓冲区,用于在程序执行大量字符串操作时提供更好的性能。StringBuilder 字符串还允许您重新分配个别字符,这些字符是内置字符串数据类型所不支持的。例如,此代码在不创建新字符串的情况下更改了一个字符串的内容:

示例:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");

sb[0] = 'C';

System.Console.WriteLine(sb.ToString()); // displays Cat: the ideal pet

System.Console.ReadLine();

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

示例:

class TestStringBuilder

{

static void Main()

{

System.Text.StringBuilder sb = new System.Text.StringBuilder();

// Create a string composed of numbers 0 - 9

for (int i = 0; i < 10; i++)

{

sb.Append(i.ToString());

}

System.Console.WriteLine(sb); // displays 0123456789

// Copy one character of the string (not possible with a System.String)

sb[0] = sb[9];

System.Console.WriteLine(sb); // displays 9123456789

}

}

四、正则表达式

可以使用 System.Text.RegularExpressions.Regex 类搜索字符串。这些搜索可以涵盖从非常简单到全面使用正则表达式的复杂范围。以下是使用 Regex 类搜索字符串的两个示例。有关更多信息,请参见 .NET Framework 正则表达式。

以下代码是一个控制台应用程序,用于对数组中的字符串执行简单的不区分大小写的搜索。给定要搜索的字符串和包含搜索模式的字符串后,静态方法 System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions) 执行搜索。

在本例中,使用第三个参数指示忽略大小写。有关更多信息,请参见 System.Text.RegularExpressions.RegexOptions。

示例:

class TestRegularExpressions

{

static void Main()

{

string[] sentences =

{

"cow over the moon",

"Betsy the Cow",

"cowering in the corner",

"no match here"

};

string sPattern = "cow";

foreach (string s in sentences)

{

System.Console.Write("{0,24}", s);

if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))

{

System.Console.WriteLine(" (match for '{0}' found)", sPattern);

}

else

{

System.Console.WriteLine();

}

}

}

}

输出:

cow over the moon (match for 'cow' found)

Betsy the Cow (match for 'cow' found)

cowering in the corner (match for 'cow' found)

no match here

以下代码是一个控制台应用程序,此程序使用正则表达式验证数组中每个字符串的格式。验证要求每个字符串具有电话号码的形式,即用短划线将数字分成三组,前两组各包含三个数字,第三组包含四个数字。这是通过正则表达式 ^//d{3}-//d{3}-//d{4}$ 完成的。有关更多信息,请参见正则表达式语言元素。

示例:

class TestRegularExpressionValidation

{

static void Main()

{

string[] numbers =

{

"123-456-7890",

"444-234-22450",

"690-203-6578",

"146-893-232",

"146-839-2322",

"4007-295-1111",

"407-295-1111",

"407-2-5555",

};

string sPattern = "^//d{3}-//d{3}-//d{4}$";

foreach (string s in numbers)

{

System.Console.Write("{0,14}", s);

if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern))

{

System.Console.WriteLine(" - valid");

}

else

{

System.Console.WriteLine(" - invalid");

}

}

}

}

输出:

123-456-7890 - valid

444-234-22450 - invalid

690-203-6578 - valid

146-893-232 - invalid

146-839-2322 - valid

4007-295-1111 - invalid

407-295-1111 - valid

407-2-5555 - invalid

五、联接多个字符串

有两种联接多个字符串的方法:使用 String 类重载的 + 运算符,以及使用 StringBuilder 类。+ 运算符使用方便,有助于生成直观的代码,但必须连续使用;每使用一次该运算符就创建一个新的字符串,因此将多个运算符串联在一起效率不高。

示例:

string two = "two";

string str = "one " + two + " three";

System.Console.WriteLine(str);

尽管在代码中只出现了四个字符串,三个字符串联接在一起,最后一个字符串包含全部三个字符串,但总共要创建五个字符串,因为首先要将前两个字符串联接,创建一个包含前两个字符串的字符串。第三个字符串是单独追加的,形成存储在 str 中的最终字符串。

也可以使用 StringBuilder 类将每个字符串添加到一个对象中,然后由该对象通过一个步骤创建最终的字符串。下面的示例对此策略进行了演示。

示例:

下面的代码使用 StringBuilder 类的 Append 方法来联接三个字符串,从而避免了串联多个 + 运算符的弊端。

示例:

class StringBuilderTest

{

static void Main()

{

string two = "two";

System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append("one ");

sb.Append(two);

sb.Append(" three");

System.Console.WriteLine(sb.ToString());

string str = sb.ToString();

System.Console.WriteLine(str);

}

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