通过附加行创建字符串

本文关键字:创建 字符串 | 更新日期: 2023-09-27 18:15:23

是否有一种直接的方法通过添加新文本作为新行来创建字符串?

我想创建一个日志样式的文本,以保持事件:

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();