簡體   English   中英

在c#中使用字符串插值連接多個字符串

[英]Concatenate multiple string using string interpolation in c#

我試過的代碼:

public void ConcatIntegers() {
  string s = "";

  for (int i = 0; i <= 5; i++) {
    s += i.ToString();
  }

  Console.WriteLine($ "{s}");
  Console.Read();
}   

在上面的方法中, + 用於連接多個值,但我一直在尋找除了 join、aggregate、concatenate 函數,而不是+符號,我想直接使用字符串interpolation ($)將連接的字符串存儲到字符串變量中。

string s = "";

for (int i = 0; i <= 5; i++) {
  // Some code which use string interpolation to 
  // concatenat multiple string and that result is stored in s 
  // variable.
}

Console.WriteLine($ "{s}");
Console.Read();

使用StringBuilder因為如果你經常這樣做,它會快得多 使用AppendFormat

StringBuilder sb = new StringBuilder();
string var1   = "abcd";
string var2   = "efgh";
sb.AppendFormat("example: {0}, {1}", var1, var2);

我會使用 String Builder 來連接字符串:

更改后的代碼:

StringBuilder sb = new StringBuilder();

string s = "";
sb.Append(s);
for (int i = 0; i <= 5; i++)
{
   sb.Append(i);
}

Console.WriteLine(sb);
Console.ReadLine();

如果你想連接,讓我們試試string.Concatstring.Join Linq 的幫助下(為了擺脫for循環),我們將得到

  using System.Linq;

  ...

  // static: we don't use "this" in the method
  public static void ConcatIntegers() {
    // Concatenate range of 0..5 integers: "012345"
    Console.WriteLine(string.Concat(Enumerable
      .Range(0, 6))); // 6 - we want 6 numbers: 0..5

    Console.Read();
  }

如果您想使用某種格式字符串插值等,請添加Select

 public static void ConcatIntegers() {
   // "000102030405" since we apply "d2" format (each number reprsented with 2 digits)
   Console.WriteLine(string.Concat(Enumerable
     .Range(0, 6)
     .Select(i => $"{i:d2}"))); // each item in 2 digits format

   Console.Read();
 }

除了 join、aggregate、concatenate 函數,我想用字符串插值($)代替 + 符號

直接將連接的字符串存儲到字符串變量中...

只需嘗試:

string result = string.Empty;
for (var i = 0; i <= 5; i++) result = $"{result}{i}";

我在 string.join 中使用字符串插值時遇到了類似的問題

        string type1 = "a,b,c";
        string[] type2 = new string[3] { "a", "b", "c" };
        
        string result = string.Join(",", $"'{x}'");

在這兩種情況下,輸出都應該是 'a','b','c'

如何對字符串數組使用 string.Join() 和字符串插值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM