一、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 \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位则前方补0M为月份数值转换的字符串 //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# System.Console.WriteLine(s4.Replace(C#, Basic)); // outputs Visual Basic Express5、Replace()格式Replace(string oldValue, string newValue)用于字符串中特定字符串组合的替换即将源字符串中的所有oldValue字符串替换为newValue字符串。示例string s5 Visual C# Express; System.Console.WriteLine(s5.Replace(C#,VB)); // outputs Visual VB Express6、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并使用结果字符串数组分别显示句子中的每个单词。示例class TestStringSplit { static void Main() { char[] delimiterChars { , ,, ., :, \t }; string text one\ttwo three:four,five six seven; System.Console.WriteLine(Original text: {0}, text); string[] words text.Split(delimiterChars); System.Console.WriteLine({0} words in text:, words.Length); foreach (string s in words) { System.Console.WriteLine(s); } } }输出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 ccc7、Trim()Trim()从当前String对象移除所有前导空白字符和尾部空白字符。示例string s7 Visual C# Express ; System.Console.WriteLine(s7); // outputs Visual C# Express System.Console.WriteLine(s7.Trim()); // outputs Visual C# Express8、ToCharArray()格式ToCharArray(int startindexint 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 fence9、利用索引访问字符串中的各个字符格式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 106611、比较比较两个字符串的最简单方法是使用和!运算符执行区分大小写的比较。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()方法它根据某个字符串是否小于 () 或大于 () 另一个返回一个整数值。比较字符串时使用 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()返回 -1否则返回它出现的第一个位置的索引从零开始。示例string s13 Battle of Hastings, 1066; System.Console.WriteLine(s13.IndexOf(Hastings)); // outputs 10 System.Console.WriteLine(s13.IndexOf(1967)); // outputs -1string类型它是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); bool test1 str.StartsWith(a silly); System.Console.WriteLine(starts with a silly? {0}, test1); bool test2 str.StartsWith(a silly, System.StringComparison.OrdinalIgnoreCase); System.Console.WriteLine(starts with a silly? {0} (ignoring case), test2); bool test3 str.EndsWith(.); System.Console.WriteLine(ends with .? {0}, test3); 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); } }输出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 三、使用 StringBuilderStringBuilder类创建了一个字符串缓冲区用于在程序执行大量字符串操作时提供更好的性能。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 } }