<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # 字符串(C# 編程指南) 字符串是 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 類型的對象,它的值是文本。在內部,文本被存儲為 [Char](https://msdn.microsoft.com/zh-CN/library/system.char.aspx) 對象的順序只讀集合。C# 字符串末尾沒有以 null 結尾的字符;因此 C# 字符串可以包含任意數目的嵌入式 null 字符(“\0”)。字符串的 [Length](https://msdn.microsoft.com/zh-CN/library/system.string.length.aspx) 屬性代表它包含的 **Char** 對象的數量,而不是 Unicode 字符的數量。若要訪問字符串中的各個 Unicode 碼位,請使用 [StringInfo](https://msdn.microsoft.com/zh-CN/library/system.globalization.stringinfo.aspx) 對象。 ## 字符串與System.String 在 C# 中,**string** 關鍵字是 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 的別名。因此,**String** 與 **string** 等效,您可以根據自己的喜好選擇命名約定。 **String** 類提供了很多用于安全地創建、操作和比較字符串的方法。此外,C# 語言還重載某些運算符來簡化常見的字符串操作。有關關鍵字的更多信息,請參見[string(C# 參考)](https://msdn.microsoft.com/zh-CN/library/362314fe.aspx)。有關類型及其方法的更多信息,請參見 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx)。 ## 聲明和初始化字符串 可以通過各種方式來聲明和初始化字符串,如下面的示例所示: ``` // 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](https://msdn.microsoft.com/zh-CN/library/fa0ab757.aspx) 運算符創建字符串對象。 使用 [Empty](https://msdn.microsoft.com/zh-CN/library/system.string.empty.aspx) 常量值初始化字符串可新建字符串長度為零的 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 對象。零長度字符串的字符串表示形式為 ""。使用 [Empty](https://msdn.microsoft.com/zh-CN/library/system.string.empty.aspx) 值(而不是 [null](https://msdn.microsoft.com/zh-CN/library/edakx9da.aspx))初始化字符串可以降低發生 [NullReferenceException](https://msdn.microsoft.com/zh-CN/library/system.nullreferenceexception.aspx) 的可能性。請在嘗試訪問字符串之前使用靜態 [IsNullOrEmpty(String)](https://msdn.microsoft.com/zh-CN/library/system.string.isnullorempty.aspx) 方法驗證字符串的值。 ## 字符串對象的不可變性 字符串對象是不可變的:即它們創建之后就無法更改。所有看似修改字符串的 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 方法和 C# 運算符實際上都以新字符串對象的形式返回結果。在下面的示例中,當連接 s1 和 s2 的內容以形成一個字符串時,不會修改兩個原始字符串。 **+=** 運算符會創建一個包含組合內容的新字符串。這個新對象賦給變量 s1,而最初賦給 s1 的對象由于沒有其他任何變量包含對它的引用而釋放,用于垃圾回收。 ``` 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. ``` 由于“修改”字符串實際上是創建新字符串,因此創建對字符串的引用時必須謹慎。如果創建了對字符串的引用,然后“修改”原始字符串,則該引用指向的仍是原始對象,而不是修改字符串時創建的新對象。下面的代碼說明了這種行為: ``` string s1 = "Hello "; string s2 = s1; s1 += "World"; System.Console.WriteLine(s2); //Output: Hello ``` 有關如何創建基于修改(例如搜索和替換原始字符串的操作)的新字符串的更多信息,請參見[如何:修改字符串內容(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228599.aspx)。 ## 正則字符串和原義字符串 如果必須嵌入 C# 提供的轉義符,則應使用正則字符串,如下面的示例所示: ``` 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 ``` 如果字符串文本包含反斜杠字符(例如在文件路徑中),為方便起見和提高可讀性,應使用原義字符串。由于原義字符串保留換行符作為字符串文本的一部分,因此可用于初始化多行字符串。在原義字符串中嵌入引號時請使用雙引號。下面的示例演示原義字符串的一些常見用途: ``` 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." ``` ## 字符串轉義序列 | 轉義序列 | 字符名稱 | Unicode 編碼 | | --- | --- | --- | | \' | 單引號 | 0x0027 | | \" | 雙引號 | 0x0022 | | \\ | 反斜杠 | 0x005C | | \0 | Null | 0x0000 | | \a | 警報 | 0x0007 | | \b | Backspace | 0x0008 | | \f | 換頁 | 0x000C | | \n | 換行 | 0x000A | | \r | 回車 | 0x000D | | \t | 水平制表符 | 0x0009 | | \U | 代理項對的 Unicode 轉義序列。 | \Unnnnnnnn | | \u | Unicode 轉義序列 | \u0041 = "A" | | \v | 垂直制表符 | 0x000B | | \x | Unicode 轉義序列類似于“\u”,只是長度可變。 | \x0041 = "A" | | ![](https://box.kancloud.cn/2016-01-31_56adb62c1380a.jpg) 注意 | | :-- | | 編譯時,原義字符串轉換為所有轉義序列均保持不變的普通字符串。因而,如果在調試器監視窗口中查看原義字符串,則看到的將是編譯器添加的轉義字符,而不是源代碼中的原義版本。例如,原義字符串 @"C:\files.txt" 在監視窗口中將顯示為 "C:\\files.txt"。 | ## 格式字符串 格式字符串是內容可以在運行時動態確定的一種字符串。采用以下方式創建格式字符串:使用靜態 [Format](https://msdn.microsoft.com/zh-CN/library/1ksz8yb7.aspx) 方法并在大括號中嵌入占位符,這些占位符將在運行時替換為其他值。下面的示例使用格式字符串輸出循環中每個迭代的結果: ``` class FormatString { static void Main() { // Get user input. System.Console.WriteLine("Enter a number"); string input = System.Console.ReadLine(); // Convert the input string to an int. int j; System.Int32.TryParse(input, out j); // Write a different string each iteration. string s; for (int i = 0; i < 10; i++) { // A simple format string with no alignment formatting. s = System.String.Format("{0} times {1} = {2}", i, j, (i * j)); System.Console.WriteLine(s); } //Keep the console window open in debug mode. System.Console.ReadKey(); } } ``` [WriteLine](https://msdn.microsoft.com/zh-CN/library/zdf6yhx5.aspx) 方法的一個重載將格式字符串用作參數。因此,可以只嵌入格式字符串,而無需顯式調用該方法。但若使用 [WriteLine](https://msdn.microsoft.com/zh-CN/library/65cydf9y.aspx) 方法在 Visual Studio**“輸出”**窗口中顯示調試輸出,則必須顯式調用 [Format](https://msdn.microsoft.com/zh-CN/library/1ksz8yb7.aspx) 方法,因為 [WriteLine](https://msdn.microsoft.com/zh-CN/library/65cydf9y.aspx) 只接受字符串,而不接受格式字符串。有關格式字符串的更多信息,請參見[.NET Framework 中的格式化類型](https://msdn.microsoft.com/zh-CN/library/26etazsy.aspx)。 ## 子字符串 子字符串是包含在字符串中的任意字符序列。使用 [Substring](https://msdn.microsoft.com/zh-CN/library/hxthx5h6.aspx) 方法可以基于原始字符串的一部分創建新字符串。可以使用 [IndexOf](https://msdn.microsoft.com/zh-CN/library/kwb0bwyd.aspx) 方法搜索子字符串的一個或多個匹配項。使用 [Replace](https://msdn.microsoft.com/zh-CN/library/czx8s9ts.aspx) 方法可將指定子字符串的所有匹配項替換為一個新字符串。與 [Substring](https://msdn.microsoft.com/zh-CN/library/hxthx5h6.aspx) 方法一樣,[Replace](https://msdn.microsoft.com/zh-CN/library/czx8s9ts.aspx) 實際上返回的也是新字符串,而不修改原始字符串。有關更多信息,請參見[如何:使用字符串方法搜索字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228630.aspx)和[如何:修改字符串內容(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228599.aspx)。 ``` 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 s5 = "Printing backwards"; for (int i = 0; i < s5.Length; i++) { System.Console.Write(s5[s5.Length - i - 1]); } // Output: "sdrawkcab gnitnirP" ``` 如果 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 方法不提供修改字符串中的各個字符所必須具有的功能,則您可以使用 [StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 對象“就地”修改各個字符,然后使用 [StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 方法創建一個新字符串來存儲結果。在下面的示例中,假設您必須以特定方式修改原始字符串,然后存儲結果以備將來使用: ``` 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 字符串和空字符串 空字符串是不包含字符的 [System.String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 對象的實例。在各種編程方案中經常會使用空字符串表示空白文本字段。可以對空字符串調用方法,因為它們是有效的 [System.String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 對象。空字符串可按如下方式初始化: ``` string s = String.Empty; ``` 相反,null 字符串并不引用 [System.String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 對象的實例,任何對 null 字符串調用方法的嘗試都會生成 [NullReferenceException](https://msdn.microsoft.com/zh-CN/library/system.nullreferenceexception.aspx)。但是,可以在串聯和比較操作中將 null 字符串與其他字符串一起使用。下面的示例闡釋了引用 null 字符串導致引發異常的情形以及并不導致引發異常的情形: ``` 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 快速創建字符串 .NET 中的字符串操作已高度優化,大多數情況下不會顯著影響性能。但在某些應用場景中,例如在執行好幾百甚至好幾千次的緊湊循環中,字符串操作會影響性能。 [StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 類創建了一個字符串緩沖區,用于在程序執行大量字符串操作時提供更好的性能。 [StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 字符串還使您能夠重新分配個別字符(內置字符串數據類型所不支持的字符)。例如,此代碼在不創建新字符串的情況下更改了一個字符串的內容: ``` 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](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 對象用于從一組數值類型中創建字符串: ``` 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 } } ``` ## 字符串、擴展方法和 LINQ 由于 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 類型實現 [IEnumerable&lt;T&gt;](https://msdn.microsoft.com/zh-CN/library/9eekhta0.aspx),因此可以對字符串使用 [Enumerable](https://msdn.microsoft.com/zh-CN/library/system.linq.enumerable.aspx) 類中定義的擴展方法。對于 [String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 類型,為了避免視覺上的混亂,從 IntelliSense 中排除了這些方法,但這些方法仍然可用。此外,還可以對字符串使用 LINQ 查詢表達式。有關更多信息,請參見 [LINQ and Strings](https://msdn.microsoft.com/zh-CN/library/bb397915.aspx)。 ## 相關主題 | 主題 | 說明 | | --- | --- | | [如何:修改字符串內容(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228599.aspx) | 提供一個代碼示例來演示如何修改字符串的內容。 | | [如何:串聯多個字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228504.aspx) | 闡釋如何使用 **+** 運算符和 **Stringbuilder** 類在編譯時和運行時將字符串聯接在一起。 | | [如何:比較字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/cc165449.aspx) | 演示如何執行字符串的序號比較。 | | [如何:拆分字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228388.aspx) | 包含一個代碼示例,該示例演示如何使用 **String.Split** 方法來分析字符串。 | | [如何:使用字符串方法搜索字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228630.aspx) | 解釋如何使用特定方法來搜索字符串。 | | [如何:使用正則表達式搜索字符串(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/ms228595.aspx) | 解釋如何使用正則表達式來搜索字符串。 | | [如何:確定字符串是否表示數值(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/bb384043.aspx) | 演示如何安全地分析字符串以了解其是否具有有效數值。 | | [如何:將字符串轉換為 DateTime(C# 編程指南)](https://msdn.microsoft.com/zh-CN/library/cc165448.aspx) | 演示如何將諸如“01/24/2008”這樣的字符串轉換為 [System.DateTime](https://msdn.microsoft.com/zh-CN/library/system.datetime.aspx) 對象。 | | [.NET Framework 中的基本字符串操作](https://msdn.microsoft.com/zh-CN/library/a292he7t.aspx) | 提供一些指向主題的鏈接,這些主題使用 [System.String](https://msdn.microsoft.com/zh-CN/library/system.string.aspx) 和 [System.Text.StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 方法來執行基本字符串操作。 | | [在 .NET Framework 中分析字符串](https://msdn.microsoft.com/zh-CN/library/b4w53z0y.aspx) | 介紹如何將字符或空格插入到字符串中。 | | [在 .NET Framework 中比較字符串](https://msdn.microsoft.com/zh-CN/library/fbh501kz.aspx) | 包含有關如何比較字符串的信息,并且提供使用 C# 和 Visual Basic 編寫的示例。 | | [在 .NET Framework 中使用 StringBuilder 類](https://msdn.microsoft.com/zh-CN/library/2839d5h5.aspx) | 描述如何使用 [StringBuilder](https://msdn.microsoft.com/zh-CN/library/system.text.stringbuilder.aspx) 類創建和修改動態字符串對象。 | | [LINQ and Strings](https://msdn.microsoft.com/zh-CN/library/bb397915.aspx) | 提供有關如何使用 LINQ 查詢來執行各種字符串操作的信息。 | | [C# 編程指南](https://msdn.microsoft.com/zh-CN/library/67ef8sbd.aspx) | 提供指向解釋 C# 中編程構造的主題的鏈接。 | ## 重要章節 [More About Variables](http://go.microsoft.com/fwlink/?LinkId=221230) 在 [Beginning Visual C# 2010](http://go.microsoft.com/fwlink/?LinkId=221214)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看