从变量中添加文本的多行字符串
本文关键字:字符串 文本 变量 添加 | 更新日期: 2023-09-27 18:10:55
我知道这会起作用的:
string multiline_text = @"this is a multiline text
this is line 1
this is line 2
this is line 3";
我如何使以下工作:
string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";
string multiline_text = @"this is a multiline text
this is " + a1 + "
this is " + a2 + "
this is " + a3 + ";
是否有可能不将字符串分成几个子字符串,每行一个?
一种选择是使用字符串格式。c# 6之前:
string pattern = @"this is a multiline text
this is {0}
this is {1}
this is {2}";
string result = string.Format(pattern, a1, a2, a3);
在c# 6中,您可以使用逐字插入的字符串字面值:
string pattern = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";
请注意,$@
必须完全是这样-如果您尝试使用@$
,它将无法编译。
虽然string.Format
是更好的实践,但要做到您想要实现的目标,只需在每行末尾添加额外的@
s:
string multiline_text = @"this is a multiline text
this is " + a1 + @"
this is " + a2 + @"
this is " + a3 + @"";
您还缺少最后一个"
在结束的分号之前。
您可以从StringBuilder
类中获得这样的可读性:
StringBuilder sb = new StringBuilder();
sb.AppendLine("this is a multiline");
sb.AppendLine("this is " + a1); // etc
var result = sb.ToString();
使用c# 6 (Visual Studio 2015),您可以编写:
string multiline_text = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";
字符串。格式将被编译器使用(就像在琼斯的回答中一样),但它更容易阅读。
由于某些原因c#不支持这样的多行文本。最接近的是:
string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";
string multiline_text = @"this is a multiline text" +
"this is " + a1 +
"this is " + a2 +
"this is " + a3;
另一个可能的解决方案与Jon Skeet的答案类似:
string result = string.Format(
"this is a multiline text{0}this is {1}{0}this is {2}{0}this is {3}",
Environment.NewLine, a1, a2, a3);
,所以基本上你插入一个新的行,你想一个{0}
。因此,它使字符串更加抽象,但这种解决方案的好处是它完全封装在string.Format
方法中。这可能不太相关,但还是值得一提。
为了好玩,您还可以使用数组连接技术来获得可读的内容并控制缩进。有时多行模板强迫你完全左对齐是不美观的…
string a1 = "London", a2 = "France", a3 = "someone's underpants";
string result = string.Join(Environment.NewLine, new[] {
$"this is {a1}", // interpolated strings look nice
"this is " + a2, // you can concat if you can't interpolate
$"this is {a3}" // these in-line comments can be nice too
});
如果必须格式化,请将连接换行以获得整洁的结果,而不是单独换行。
从c# 11和。net 7开始,可以使用支持插值的原始字符串字面值:
string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";
string multiline_text = $"""
this is a multiline text
this is {a1}
this is {a2}
this is {a3}
""";