字符串

更新:2007 年 11 月

C# 字符串是使用 string 关键字声明的、由一个或多个字符构成的一组字符,string 关键字是 C# 语言中对应于 System.String 类的快捷方式。C# 中的字符串比 C 或 C++ 中的字符数组更易于使用,而且也较不容易发生编程错误。

字符串是使用引号声明的,如下面的示例所示:

string greeting = "Hello, World!";

您可以提取子字符串,并连接字符串,如下所示:

string s1 = "A string is more ";
string s2 = "than the sum of its chars.";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;

System.Console.WriteLine(s1);
// Output: A string is more than the sum of its chars.

字符串对象不可变,因此一旦创建就不能更改。对字符串进行操作的方法实际会返回新的字符串对象。因此,出于性能方面的考虑,大量连接或其他涉及的字符串操作应通过 StringBuilder 类来执行,如下面的代码示例所示。

使用字符串

转义符

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

string columns = "Column 1\tColumn 2\tColumn 3";
//Output: Column 1        Column 2        Column 3

string rows = "Row 1\r\nRow 2\r\nRow 3";
/* Output:
  Row 1
  Row 2
  Row 3
*/

string title = "\"The \u00C6olean Harp\", by Samuel Taylor Coleridge";
//Output: "The Æolean Harp", by Samuel Taylor Coleridge

等同于:

Hello

World!

如果要包括反斜杠,则必须在前面放置另一个反斜杠。下面的字符串:

         string filePath = @"C:\Users\scoleridge\Documents\";
         //Output: C:\Users\scoleridge\Documents\

         string text = @"My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,...";
         /* Output:
         My pensive SARA ! thy soft cheek reclined
            Thus on mine arm, most soothing sweet it is
            To sit beside our Cot,... 
         */

         string quote = @"Her name was ""Sara.""";
         //Output: Her name was "Sara."

完全等同于:

\\My Documents\

@ 符号

@ 符号指定在创建字符串时必须忽略转义符和换行符。因此下面的两个字符串是相同的:

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @"\\My Documents\My Files\";

ToString()

C# 内置数据类型都提供了 ToString 方法,用于将值转换为字符串。此方法可以用于将数值转换为字符串,如下所示:

int year = 1999;
string msg = "Eve was born in " + year.ToString();
System.Console.WriteLine(msg);  // outputs "Eve was born in 1999"

访问各个字符

字符串中包含的各个字符可以使用如下的方法进行访问:SubstringReplaceSplitTrim

string s3 = "Visual C# Express";
System.Console.WriteLine(s3.Substring(7, 2));
// Output: "C#"

System.Console.WriteLine(s3.Replace("C#", "Basic"));
// Output: "Visual Basic Express"

// Index values are zero-based
int index = s3.IndexOf("C");
// index = 7

也可以将字符复制到字符数组中,如下所示:

string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?";
System.Text.StringBuilder sb = new System.Text.StringBuilder(question);

for (int j = 0; j < sb.Length; j++)
{
    if (System.Char.IsLower(sb[j]) == true)
        sb[j] = System.Char.ToUpper(sb[j]);
    else if (System.Char.IsUpper(sb[j]) == true)
        sb[j] = System.Char.ToLower(sb[j]);
}
// Store the new string.
string corrected = sb.ToString();
System.Console.WriteLine(corrected);
// Output: How does Microsoft Word deal with the Caps Lock key?            

字符串中的单个字符可以通过索引访问,如下所示:

string s5 = "Printing backwards";

for (int i = 0; i < s5.Length; i++)
{
    System.Console.Write(s5[s5.Length - i - 1]);
}
// Output: "sdrawkcab gnitnirP"

更改大小写

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

string s6 = "Battle of Hastings, 1066";

System.Console.WriteLine(s6.ToUpper());
// outputs "BATTLE OF HASTINGS 1066"
System.Console.WriteLine(s6.ToLower());
// outputs "battle of hastings 1066"

比较

比较两个未本地化字符串的最好方法是使用具有 StringComparison.Ordinal 和 StringComparison.OrdinalIgnoreCase 的 Equals 方法。

// Internal strings that will never be localized.
string root = @"C:\users";
string root2 = @"C:\Users";

// Use the overload of the Equals method that specifies a StringComparison.
// Ordinal is the fastest way to compare two strings.
bool result = root.Equals(root2, StringComparison.Ordinal);

Console.WriteLine("Ordinal comparison: {0} and {1} are {2}", root, root2,
                    result ? "equal." : "not equal.");

// To ignore case means "user" equals "User". This is the same as using
// String.ToUpperInvariant on each string and then performing an ordinal comparison.
result = root.Equals(root2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ordinal ignore case: {0} and {1} are {2}", root, root2,
                     result ? "equal." : "not equal.");

// A static method is also available.
bool areEqual = String.Equals(root, root2, StringComparison.Ordinal);


// String interning. Are these really two distinct objects?
string a = "The computer ate my source code.";
string b = "The computer ate my source code.";

// ReferenceEquals returns true if both objects
// point to the same location in memory.
if (String.ReferenceEquals(a, b))
    Console.WriteLine("a and b are interned.");
else
    Console.WriteLine("a and b are not interned.");

// Use String.Copy method to avoid interning.
string c = String.Copy(a);

if (String.ReferenceEquals(a, c))
    Console.WriteLine("a and c are interned.");
else
    Console.WriteLine("a and c are not interned.");

字符串对象还有 CompareTo() 方法,用于根据一个字符串是小于 (<) 还是大于 (>) 另一个字符串来返回一个整数值。比较字符串时使用的是 Unicode 值,并且小写的值小于大写的值。

// Enter different values for string1 and string2 to
// experiement with behavior of CompareTo
string string1 = "ABC";
string string2 = "abc";

int result2 = string1.CompareTo(string2);

if (result2 > 0)
{
    System.Console.WriteLine("{0} is greater than {1}", string1, string2);
}
else if (result2 == 0)
{
    System.Console.WriteLine("{0} is equal to {1}", string1, string2);
}
else if (result2 < 0)
{
    System.Console.WriteLine("{0} is less than {1}", string1, string2);
}
// Output: ABC is less than abc

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

// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

// Alternate choice: If the string has been input by an end user, you might 
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);

/* Output (assuming first culture is en-US and second is fr-FR):
    Year: 2008, Month: 1, Day: 8
    Year: 2008, Month: 8, Day 1
 */

将字符串拆分为子字符串

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

string numString = "1287543"; //"1287543.0" will return false for a long
long number1 = 0;
bool canConvert = long.TryParse(numString, out number1);
if (canConvert == true)
  Console.WriteLine("number1 now = {0}", number1);
else
  Console.WriteLine("numString is not a valid long");

byte number2 = 0;
numString = "255"; // A value of 256 will return false
canConvert = byte.TryParse(numString, out number2);
if (canConvert == true)
  Console.WriteLine("number2 now = {0}", number2);
else
  Console.WriteLine("numString is not a valid byte");

decimal number3 = 0;
numString = "27.3"; //"27" is also a valid decimal
canConvert = decimal.TryParse(numString, out number3);
if (canConvert == true)
  Console.WriteLine("number3 now = {0}", number3);
else
  Console.WriteLine("number3 is not a valid decimal");            

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

The

cat

sat

on

the

mat.

使用 StringBuilder

StringBuilder 类创建一个字符串缓冲区,用于在程序执行大量字符串操作时提供更好的性能。StringBuilder 类还允许重新分配单个字符,这是内置字符串数据类型所不支持的。

在此示例中,创建一个 StringBuilder 对象,并使用 Append 方法逐一添加其内容。

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

请参见

任务

如何:生成多行字符串 (Visual C#)

如何:在字符串数组中搜索字符串

如何:在字符串内进行搜索

概念

C# 语言入门

内置数据类型(Visual C# 速成版)

参考

string(C# 参考)