Share via


HOW TO:串連多個字串 (C# 程式設計手冊)

「串連」(Concatenation) 是將某一個字串附加至另一個字串結尾的程序。 使用 + 運算子串連字串常值 (String Literal) 或字串常數時,編譯器會建立單一字串。 執行階段不會發生串連作業, 但只有在執行階段才可以串連字串變數。 針對此種案例,您應該要了解各種方式的效能含意。

範例

在下列範例中,會示範如何將長字串常值分割成較小字串,以增加原始程式碼的易讀性。 在編譯時期,這些分割部分將串連成單一字串。 不管包含多少字串,都不會耗用任何執行階段效能。

static void Main()
{
    // Concatenation of literals is performed at compile time, not run time.
    string text = "Historically, the world of data and the world of objects " +
    "have not been well integrated. Programmers work in C# or Visual Basic " +
    "and also in SQL or XQuery. On the one side are concepts such as classes, " +
    "objects, fields, inheritance, and .NET Framework APIs. On the other side " +
    "are tables, columns, rows, nodes, and separate languages for dealing with " +
    "them. Data types often require translation between the two worlds; there are " +
    "different standard functions. Because the object world has no notion of query, a " +
    "query can only be represented as a string without compile-time type checking or " +
    "IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to " +
    "objects in memory is often tedious and error-prone.";

    Console.WriteLine(text);
}

若要串連字串變數,您可以使用 + 或 += 運算子,或是 String.ConcatString.FormatStringBuilder.Append 方法。 + 運算子很容易使用,有利於程式撰寫人員按照直覺來撰寫程式碼。 即使您在一個陳述式中使用數個 + 運算子,字串內容仍只會複製一次。 但如果您多次重複執行這種運算 (例如在迴圈中),則可能會造成效率問題。 例如,請注意下列程式碼:

static void Main(string[] args)
{
    // To run this program, provide a command line string.
    // In Visual Studio, see Project > Properties > Debug.
    string userName = args[0];
    string date = DateTime.Today.ToShortDateString();

    // Use the + and += operators for one-time concatenations.
    string str = "Hello " + userName + ". Today is " + date + ".";
    System.Console.WriteLine(str);

    str += " How are you today?";
    System.Console.WriteLine(str);

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}

// Example output: 
//  Hello Alexander. Today is 1/22/2008.
//  Hello Alexander. Today is 1/22/2008. How are you today?
//  Press any key to exit.
//
注意事項注意事項

在字串的串連作業中,C# 編譯器會將 null 字串視為與空字串相同,但不會轉換原始 null 字串的值。

如果不是串連大量的字串 (例如在迴圈中),執行這個程式碼所耗用的效能可能不值得一提。 對 String.ConcatString.Format 方法來說,這同樣是成立的。

不過,當效能很重要時,一定要使用 StringBuilder 類別 (Class) 來串連字串。 下列程式碼會使用 StringBuilder 類別的 Append 方法來串連字串,並沒有 + 運算子的鏈結效果。

class StringBuilderTest
{
    static void Main()
    {
        string text = null;

        // Use StringBuilder for concatenation in tight loops.
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 100; i++)
        {
            sb.AppendLine(i.ToString());
        }
        System.Console.WriteLine(sb.ToString());

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
// Output:
// 0
// 1
// 2
// 3
// 4
// ...
//

請參閱

參考

String

StringBuilder

概念

C# 程式設計手冊

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