是否有通过将新文字添加为新行来创建字符串的简单方法?
我想创建一个日志样式的文本,用于保存事件:
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);
有更好的方法吗?
答案 0 :(得分:3)
您也可以使用 StringBuilder 。这非常有效。
StringBuilder builder = new StringBuilder();
builder.AppendLine("Something happended");
builder.AppendLine("Wow ");
如果你做了很多,那么可能会更有效率,因为它不会创建大量的临时字符串。
答案 1 :(得分:3)
改为使用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
),所以如果您知道它将是什么,请使用该重载,因为它将避免昂贵的内部大小调整缓冲液中。
答案 2 :(得分:2)
是的,使用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();
答案 3 :(得分:1)
您可以使用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();
答案 4 :(得分:0)
您可以使用字符串构建器并附加
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();