Computer >> Máy Tính >  >> Lập trình >> C#

Lặp lại C # StringBuilder trong một vòng lặp foreach

Đầu tiên, đặt một mảng chuỗi và StringBuilder -

// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();

Bây giờ, hãy sử dụng vòng lặp foreach để lặp lại -

foreach (string item in myStr) {
   str.Append(item).AppendLine();
}

Sau đây là mã hoàn chỉnh -

Ví dụ

using System;
using System.Text;

public class Demo {
   public static void Main() {
      // string array
      string[] myStr = { "One", "Two", "Three", "Four" };
      StringBuilder str = new StringBuilder("We will print now...").AppendLine();

      // foreach loop to append elements
      foreach (string item in myStr) {
         str.Append(item).AppendLine();
      }
      Console.WriteLine(str.ToString());
      Console.ReadLine();
   }
}

Đầu ra

We will print now...
One
Two
Three
Four