字串 (C# 程式設計手冊)Strings (C# Programming Guide)

字串是 String 類型的物件,其值為文字。A string is an object of type String whose value is text. 就內部而言,文字會儲存為 Char 物件的循序唯讀集合。Internally, the text is stored as a sequential read-only collection of Char objects. C# 字串的結尾沒有終止的 Null 字元,因此 C# 字串可以包含任何數目的內嵌 Null 字元 ('\0')。There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). 字串的 Length 屬性代表它包含的 Char 物件數目,而非 Unicode 字元的數目。The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters. 若要存取字串中的個別 Unicode 字碼指標,請使用 StringInfo 物件。To access the individual Unicode code points in a string, use the StringInfo object.

字串與System.Stringstring vs. System.String

在 C# 中,string 關鍵字是 String 的別名。In C#, the string keyword is an alias for String. 因此 Stringstring 為相等,而您可以使用您偏好的命名慣例。Therefore, String and string are equivalent, and you can use whichever naming convention you prefer. String 類別提供許多方法來安全地建立、操作和比較字串。The String class provides many methods for safely creating, manipulating, and comparing strings. 此外,C# 語言會多載一些運算子,以簡化常見的字串作業。In addition, the C# language overloads some operators to simplify common string operations. 如需關鍵字的詳細資訊,請參閱字串For more information about the keyword, see string. 如需類型和其方法的詳細資訊,請參閱 StringFor more information about the type and its methods, see String.

宣告並初始化字串Declaring and Initializing Strings

您可以透過多種方式宣告並初始化字串,如下列範例所示:You can declare and initialize strings in various ways, as shown in the following example:

// Declare without initializing.
string message1;

// Initialize to null.
string message2 = null;

// Initialize as an empty string.
// Use the Empty constant instead of the literal "".
string message3 = System.String.Empty;

//Initialize with a regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";

// Initialize with a verbatim string literal.
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";

// Use System.String if you prefer.
System.String greeting = "Hello World!";

// In local variables (i.e. within a method body)
// you can use implicit typing.
var temp = "I'm still a strongly-typed System.String!";

// Use a const string to prevent 'message4' from
// being used to store another string value.
const string message4 = "You can't get rid of me!";

// Use the String constructor only when creating
// a string from a char*, char[], or sbyte*. See
// System.String documentation for details.
char[] letters = { 'A', 'B', 'C' };
string alphabet = new string(letters);

請注意,除了使用字元陣列初始化字串以外,您不能使用 new 運算子建立字串物件。Note that you do not use the new operator to create a string object except when initializing the string with an array of chars.

使用 Empty 常數值初始化字串,以建立字串長度為零的新 String 物件。Initialize a string with the Empty constant value to create a new String object whose string is of zero length. 零長度字串的字串常值表示法是 ""。The string literal representation of a zero-length string is "". 使用 Empty 值初始化字串,而非 null,即可降低發生 NullReferenceException 的機會。By initializing strings with the Empty value instead of null, you can reduce the chances of a NullReferenceException occurring. 使用靜態 IsNullOrEmpty(String) 方法,先驗證字串的值,再嘗試進行存取。Use the static IsNullOrEmpty(String) method to verify the value of a string before you try to access it.

字串物件的不變性Immutability of String Objects

字串物件為「不可變」 :它們在建立之後將無法變更。String objects are immutable: they cannot be changed after they have been created. 所有看似會修改字串的 String 方法和 C# 運算子,實際上會以新的字串物件傳回結果。All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. 在下列範例中,當 s1s2 的內容串連以組成單一字串時,兩個原始字串將不會被修改。In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. += 運算子會建立新的字串,其中包含結合的內容。The += operator creates a new string that contains the combined contents. 新的物件會指派給變數 s1,而先前指派給 s1 的原始物件將會被釋放以進行記憶體回收,因為已經沒有其他具有其參考的變數。That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

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.

因為對字串的「修改」實際上是建立新的字串,當您建立對字串的參考時,必須特別謹慎。Because a string "modification" is actually a new string creation, you must use caution when you create references to strings. 如果您建立對字串的參考,然後「修改」原始字串,該參考將會繼續指向原始物件,而非修改字串時所建立的新物件。If you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified. 下列程式碼說明這個行為:The following code illustrates this behavior:

string s1 = "Hello ";
string s2 = s1;
s1 += "World";

System.Console.WriteLine(s2);
//Output: Hello

如需如何建立以修改為基礎 (例如原始字串上的搜尋與取代作業) 之新字串的詳細資訊,請參閱如何:修改字串內容For more information about how to create new strings that are based on modifications such as search and replace operations on the original string, see How to: Modify String Contents.

一般和逐字字串常值Regular and Verbatim String Literals

當您必須內嵌由 C# 所提供的逸出字元時,請使用一般字串常值,如下列範例所示︰Use regular string literals when you must embed escape characters provided by C#, as shown in the following example:

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

當字串文字包含反斜線字元時 (例如檔案路徑),基於方便性和可讀性,請使用逐字字串。Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. 因為逐字字串會將新行字元保留為字串文字的一部分,因此可以將它們用來初始化多行字串。Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. 使用雙引號在逐字字串中內嵌引號。Use double quotation marks to embed a quotation mark inside a verbatim string. 下列範例示範一些逐字字串的常見用法︰The following example shows some common uses for verbatim strings:

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

字串逸出序列String Escape Sequences

逸出序列Escape sequence 字元名稱Character name Unicode 編碼Unicode encoding
\'\' 單引號Single quote 0x00270x0027
\"\" 雙引號Double quote 0x00220x0022
\\ 反斜線Backslash 0x005C0x005C
\0\0 NullNull 0x00000x0000
\a\a 警示Alert 0x00070x0007
\b\b 退格鍵Backspace 0x00080x0008
\f\f 換頁字元Form feed 0x000C0x000C
\n\n 換行New line 0x000A0x000A
\r\r 歸位字元Carriage return 0x000D0x000D
\t\t 水平 TabHorizontal tab 0x00090x0009
\v\v 垂直 TabVertical tab 0x000B0x000B
\u\u Unicode 逸出序列 (UTF-16)Unicode escape sequence (UTF-16) \uHHHH (範圍:0000 - FFFF;範例:\u00E7 = "ç")\uHHHH (range: 0000 - FFFF; example: \u00E7 = "ç")
\U\U Unicode 逸出序列 (UTF-32)Unicode escape sequence (UTF-32) \U00HHHHHH (範圍:000000 - 10FFFF;範例:\U0001F47D = "👽")\U00HHHHHH (range: 000000 - 10FFFF; example: \U0001F47D = "👽")
\x\x 類似 "\u" (除了變數長度之外) 的 Unicode 逸出序列Unicode escape sequence similar to "\u" except with variable length \xH[H][H][H] (範圍:0 - FFFF;範例:\x00E7\x0E7\xE7 = "ç")\xH[H][H][H] (range: 0 - FFFF; example: \x00E7 or \x0E7 or \xE7 = "ç")

警告

當使用 \x 逸出序列且指定的十六進位數字少於 4 個時,若尾隨在逸出序列之後的字元是有效的十六進位數字 (亦即 0-9、A-F 及 a-f),這些數字將會被解譯為逸出序列的一部分。When using the \x escape sequence and specifying less than 4 hex digits, if the characters that immediately follow the escape sequence are valid hex digits (i.e. 0-9, A-F, and a-f), they will be interpreted as being part of the escape sequence. 例如 \xA1 會產生 "¡",亦即字碼元素 U+00A1。For example, \xA1 produces "¡", which is code point U+00A1. 倘若下一個字元為 "A" 或 "a",則逸出序列將會被解譯為 \xA1A,進而產生 "ਚ",亦即字碼元素 U+0A1A。However, if the next character is "A" or "a", then the escape sequence will instead be interpreted as being \xA1A and produce "ਚ", which is code point U+0A1A. 由此可知,將 4 個數字全數指定為十六進位數字 (例如 \x00A1),將可避免可能的錯譯。In such cases, specifying all 4 hex digits (e.g. \x00A1 ) will prevent any possible misinterpretation.

注意

在編譯時期,逐字字串會轉換為具有所有相同逸出序列的一般字串。At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. 因此,如果您在偵錯工具監看式視窗中檢視逐字字串,您會看到由編譯器新增的逸出字元,而非來自於您原始程式碼的逐字版本。Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. 例如,逐字字串 @"C:\files.txt" 會在監看式視窗中顯示為 "C:\\files.txt"。For example, the verbatim string @"C:\files.txt" will appear in the watch window as "C:\\files.txt".

格式字串Format Strings

格式字串是可在執行階段動態決定其內容的字串。A format string is a string whose contents are determined dynamically at runtime. 格式字串是透過內嵌「插入的運算式」 或字串內大括弧內的預留位置來建立的。Format strings are created by embedding interpolated expressions or placeholders inside of braces within a string. 大括弧 ({...}) 內的所有內容都會被解析為一個值並在執行階段以格式化字串形式輸出。Everything inside the braces ({...}) will be resolved to a value and output as a formatted string at runtime. 有兩種方式可用來建立格式字串:字串插補與複合格式設定。There are two methods to create format strings: string interpolation and composite formatting.

字串插值String Interpolation

C# 6.0 與更新版本中提供的插補字串可透過 $ 特殊字元識別,而且在大括弧中包括插補運算式。Available in C# 6.0 and later, interpolated strings are identified by the $ special character and include interpolated expressions in braces. 如果您是字串插補的新手,請參閱字串插補 - C# 互動式教學課程以取得快速概觀。If you are new to string interpolation, see the String interpolation - C# interactive tutorial for a quick overview.

使用字串插補來改進您程式碼的可讀性與可維護性。Use string interpolation to improve the readability and maintainability of your code. 字串插補可達成與 String.Format 方法相同的結果,但可改進使用方便性與內嵌簡潔度。String interpolation achieves the same results as the String.Format method, but improves ease of use and inline clarity.

var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) * 100d} years old today.");

// Output:
// Jupiter Hammon was an African American poet born in 1711.
// He was first published in 1761 at the age of 50.
// He'd be over 300 years old today. 

複合格式Composite Formatting

String.Format 利用大括弧內的預留位置來建立格式字串。The String.Format utilizes placeholders in braces to create a format string. 此範例可產生與上面使用之字串插補方法類似的輸出。This example results in similar output to the string interpolation method used above.

var pw = (firstName: "Phillis", lastName: "Wheatley", born: 1753, published: 1773);
Console.WriteLine("{0} {1} was an African American poet born in {2}.", pw.firstName, pw.lastName, pw.born);
Console.WriteLine("She was first published in {0} at the age of {1}.", pw.published, pw.published - pw.born);
Console.WriteLine("She'd be over {0} years old today.", Math.Round((2018d - pw.born) / 100d) * 100d);

// Output:
// Phillis Wheatley was an African American poet born in 1753.
// She was first published in 1773 at the age of 20.
// She'd be over 300 years old today.

如需設定 .NET 類型格式的詳細資訊,請參閱 .NET 中的格式設定類型For more information on formatting .NET types see Formatting Types in .NET.

子字串Substrings

子字串是包含在字串中的任何字元序列。A substring is any sequence of characters that is contained in a string. 使用 Substring 方法,來從原始字串的一部分建立新的字串。Use the Substring method to create a new string from a part of the original string. 您可以使用 IndexOf 方法,來搜尋子字串的一或多個出現位置。You can search for one or more occurrences of a substring by using the IndexOf method. 使用 Replace 方法,以新字串取代所有指定的子字串。Use the Replace method to replace all occurrences of a specified substring with a new string. Substring 方法類似,Replace 實際上會傳回新字串,並不會修改原始字串。Like the Substring method, Replace actually returns a new string and does not modify the original string. 如需詳細資訊,請參閱如何︰搜尋字串如何︰修改字串內容For more information, see How to: search strings and How to: Modify String Contents.

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

存取個別字元Accessing Individual Characters

您可以搭配索引值使用陣列標記法來取得個別字元的唯讀存取權,如下列範例所示:You can use array notation with an index value to acquire read-only access to individual characters, as in the following example:

string s5 = "Printing backwards";

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

如果 String 方法不提供修改字串中個別字元的必要功能,您可以使用 StringBuilder 物件「就地」修改個別字元,然後使用 StringBuilder 方法建立新的字串來儲存結果。If the String methods do not provide the functionality that you must have to modify individual characters in a string, you can use a StringBuilder object to modify the individual chars "in-place", and then create a new string to store the results by using the StringBuilder methods. 在下列範例中,假設您必須以特定方式修改原始字串,並儲存結果以供日後使用︰In the following example, assume that you must modify the original string in a particular way and then store the results for future use:

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?            

Null 字串和空字串Null Strings and Empty Strings

空字串是 System.String 物件的執行個體,其中包含零個字元。An empty string is an instance of a System.String object that contains zero characters. 空字串經常用於各種程式設計案例中,來表示空白的文字欄位。Empty strings are used often in various programming scenarios to represent a blank text field. 您可以對空字串呼叫方法,因為它們是有效的 System.String 物件。You can call methods on empty strings because they are valid System.String objects. 空字串會以下列方式初始化︰Empty strings are initialized as follows:

string s = String.Empty;  

相較之下,Null 字串指的不是 System.String 物件執行個體,而且對 Null 字串呼叫方法的任何嘗試都會導致 NullReferenceExceptionBy contrast, a null string does not refer to an instance of a System.String object and any attempt to call a method on a null string causes a NullReferenceException. 不過,您可以在搭配其他字串的串連和比較作業中使用 Null 字串。However, you can use null strings in concatenation and comparison operations with other strings. 下列範例說明對 Null 字串的參考會造成 (以及不會造成) 擲回例外狀況的一些情況︰The following examples illustrate some cases in which a reference to a null string does and does not cause an exception to be thrown:

static void Main()
{
    string str = "hello";
    string nullStr = null;
    string emptyStr = String.Empty;

    string tempStr = str + nullStr;
    // Output of the following line: hello
    Console.WriteLine(tempStr);

    bool b = (emptyStr == nullStr);
    // Output of the following line: False
    Console.WriteLine(b);

    // The following line creates a new empty string.
    string newStr = emptyStr + nullStr;

    // Null strings and empty strings behave differently. The following
    // two lines display 0.
    Console.WriteLine(emptyStr.Length);
    Console.WriteLine(newStr.Length);
    // The following line raises a NullReferenceException.
    //Console.WriteLine(nullStr.Length);

    // The null character can be displayed and counted, like other chars.
    string s1 = "\x0" + "abc";
    string s2 = "abc" + "\x0";
    // Output of the following line: * abc*
    Console.WriteLine("*" + s1 + "*");
    // Output of the following line: *abc *
    Console.WriteLine("*" + s2 + "*");
    // Output of the following line: 4
    Console.WriteLine(s2.Length);
}

使用 StringBuilder 進行快速字串建立Using StringBuilder for Fast String Creation

.NET 中的字串作業已高度最佳化,在大部分的情況下不會大幅影響效能。String operations in .NET are highly optimized and in most cases do not significantly impact performance. 不過,在部分案例中 (例如執行數百或數千次的緊密迴圈),字串作業可能會影響效能。However, in some scenarios such as tight loops that are executing many hundreds or thousands of times, string operations can affect performance. StringBuilder 類別會建立一個字串緩衝區,能在您的程式執行許多字串操作的情況下提供較佳的效能。The StringBuilder class creates a string buffer that offers better performance if your program performs many string manipulations. StringBuilder 字串也可讓您重新指派內建字串資料類型所不支援的個別字元。The StringBuilder string also enables you to reassign individual characters, something the built-in string data type does not support. 例如,下列程式碼能在不建立新字串的情況下變更字串內容:This code, for example, changes the content of a string without creating a new string:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb[0] = 'C';
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();

//Outputs Cat: the ideal pet

在下列範例中,將使用 StringBuilder 物件從一組數字類型建立字串:In this example, a StringBuilder object is used to create a string from a set of numeric types:

using System;
using System.Text;

namespace CSRefStrings
{
    class TestStringBuilder
    {
        static void Main()
        {
            var sb = new StringBuilder();

            // Create a string composed of numbers 0 - 9
            for (int i = 0; i < 10; i++)
            {
                sb.Append(i.ToString());
            }
            Console.WriteLine(sb);  // displays 0123456789

            // Copy one character of the string (not possible with a System.String)
            sb[0] = sb[9];

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

字串、擴充方法和 LINQStrings, Extension Methods and LINQ

因為 String 類型會實作 IEnumerable<T>,所以您可以對字串使用 Enumerable 類別中所定義的擴充方法。Because the String type implements IEnumerable<T>, you can use the extension methods defined in the Enumerable class on strings. 為了避免視覺雜亂,這些方法會從 String 類型的 IntelliSense 中排除,不過您還是可以使用它們。To avoid visual clutter, these methods are excluded from IntelliSense for the String type, but they are available nevertheless. 您也可以在字串上使用 LINQLINQ 查詢運算式。You can also use LINQLINQ query expressions on strings. 如需詳細資訊,請參閱 LINQ 和字串For more information, see LINQ and Strings.

主題Topic 說明Description
如何:修改字串內容How to: Modify String Contents 說明轉換字串及修改字串內容的技術。Illustrates techniques to transform strings and modify the contents of strings.
如何:比較字串How to: Compare Strings 示範如何執行字串的序數與文化特定比較。Shows how to perform ordinal and culture specific comparisons of strings.
如何:串連多個字串How to: Concatenate Multiple Strings 示範如何將多個字串聯結成一個的各種方式。Demonstrates various ways to join multiple strings into one.
如何:使用 String.Split 剖析字串How to: Parse Strings Using String.Split 包含說明如何使用 String.Split 方法剖析字串的程式碼範例。Contains code examples that illustrate how to use the String.Split method to parse strings.
如何:搜尋字串How to: Search Strings 說明如何對字串中的特定文字或模式使用搜尋。Explains how to use search for specific text or patterns in strings.
如何:判斷字串是否代表數值How to: Determine Whether a String Represents a Numeric Value 示範如何安全地剖析字串,以查看它是否有有效的數值。Shows how to safely parse a string to see whether it has a valid numeric value.
字串內插補點String interpolation 描述可提供方便語法以設定格式字串的字串內插補點功能。Describes the string interpolation feature that provides a convenient syntax to format strings.
基本字串作業Basic String Operations 提供使用 System.StringSystem.Text.StringBuilder 方法執行基本字串作業之主題的連結。Provides links to topics that use System.String and System.Text.StringBuilder methods to perform basic string operations.
剖析字串Parsing Strings 描述如何將.NET 基底類型的字串表示轉換成對應類型的執行個體。Describes how to convert string representations of .NET base types to instances of the corresponding types.
在 .NET 中剖析日期和時間字串Parsing Date and Time Strings in .NET 示範如何將 "01/24/2008" 這類字串轉換為 System.DateTime 物件。Shows how to convert a string such as "01/24/2008" to a System.DateTime object.
比較字串Comparing Strings 包含如何比較字串的相關資訊,並提供以 C# 和 Visual Basic 撰寫的範例。Includes information about how to compare strings and provides examples in C# and Visual Basic.
使用 StringBuilder 類別Using the StringBuilder Class 描述如何使用 StringBuilder 類別來建立及修改動態字串物件。Describes how to create and modify dynamic string objects by using the StringBuilder class.
LINQ 和字串LINQ and Strings 提供如何使用 LINQ 查詢來執行各種字串作業的相關資訊。Provides information about how to perform various string operations by using LINQ queries.
C# 程式設計指南C# Programming Guide 提供說明 C# 中程式設計建構的主題連結。Provides links to topics that explain programming constructs in C#.