有时我想连接两个字符串,中间有一个空格。但如果第二个字符串为空,我就不需要空格了。
考虑以下代码:
void AssertFoo(bool cond, string message = null) {
...
Assert.Fail("Something is foo.{0}", message != null ? " " + message : "");
...
}
有没有更优雅的方式来做到这一点?
最佳答案
这是我喜欢的一个选项。如果你已经有一个 IEnumerable<string>
就更好了使用您的数据,但即使您不这样做也很容易。它也可以很好地扩展到连接的 n 个字符串,而不仅仅是 1 个或两个。
string[] myStrings = new string[]{"Hello", "World", null};
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
这是另一种选择。对于这个案例来说它有点短,但它更难看,更难阅读,而且可扩展性也不强,所以我个人可能会避免使用它:
//note space added before {0}
Assert.Fail("Something is foo. {0}", message ?? "\b");
在这种情况下,我们将空格添加到格式字符串本身,但如果 message
为 null,我们改为使用退格符删除我们知道在消息中它之前的空格。
关于c# - 如果字符串非空则添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12588389/