簡體   English   中英

通過添加行來創建字符串?

[英]Create a string by appending lines?

是否有通過添加新文本作為新行來創建字符串的簡單方法?

我想創建一個日志樣式的文本,以便保留事件:

Something superb happened
Wow, that is awesome
Look, a super awesome event here
A little event there
Whoops, an error here

我發現的基本上是..沒有什么新鮮的

List<string> output = new List<string>();
output.add("Something superb happened");
output.add("Wow, that is awesome");
output.add("Look, a super awesome event here");
output.add("A little event there");
output.add("Whoops, an error here");
string finalOutput = string.Join(Environment.NewLine, output);

有沒有更好的辦法?

您也可以使用StringBuilder 這是非常有效的。

StringBuilder builder = new StringBuilder();
builder.AppendLine("Something happended");
builder.AppendLine("Wow ");

如果您經常執行此操作,則可能會比不使用臨時字符串更高效,因為它不會創建大量臨時字符串。

請改用StringBuilder類。

var sb = new StringBuilder();
sb.AppendLine("Something superb happened");
sb.AppendLine("Wow, that is awesome");
sb.AppendLine("Look, a super awesome event here");
sb.AppendLine("A little event there");
sb.AppendLine("Whoops, an error here");

string finalOutput = sb.ToString();

請注意,它具有一個構造函數重載,該重載占用了初始容量(作為int ),因此,如果您對將要使用的重載有所了解,請使用該重載,因為這樣可以避免內部緩沖區的調整大小。

是的,使用StringBuilder。

System.Text.StringBuilder sbText = new System.Text.StringBuilder(500);

sbText.AppendLine("Something superb happened");
sbText.AppendLine("Wow, that is awesome");

string finalOutput = sbText.ToString();

您可以使用StringBuilder將多行有效地串聯到一個String 尤其是在您進行了很多字符串修改(例如附加行等)的情況下。

例:

var output = new StringBuilder();
output.AppendLine("Something superb happened");
output.AppendLine("Wow, that is awesome");
output.AppendLine("Look, a super awesome event here");
output.AppendLine("A little event there");
output.AppendLine("Whoops, an error here");
string finalOutput = output.ToString();

您可以使用字符串生成器並追加

StringBuilder output = new StringBuilder();
output.Append("Something superb happened"+Environment.NewLine);
output.Append("Wow, that is awesome"+Environment.NewLine);
output.Append("Look, a super awesome event here"+Environment.NewLine);
output.Append("A little event there"+Environment.NewLine);
output.Append("Whoops, an error here"+Environment.NewLine);

string finalOutput = output.ToString();

暫無
暫無

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

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