简体   繁体   English

C#-在两个字符串之间添加空格

[英]C# - Add a whitespace between two strings

I have code to display a vehicle by its Make and Model. 我有代码按其品牌和型号来显示车辆。

productName.Text = p.Make  + p.Model

The above code displays the text as such: "BentleyContinental", how can I make the text display as such "Bentley Continental". 上面的代码将文本显示为:“ BentleyContinental”,如何使文本显示为“ Bentley Continental”。

You can use string.Format() : 您可以使用string.Format()

productName.Text = string.Format("{0} {1}", p.Make, p.Model);

Or you can use string interpolation (if you are on C# 6 or higher): 或者,您可以使用字符串插值 (如果您使用的是C#6或更高版本):

productName.Text = $"{p.Make} {p.Model}";

Or you can do just as you have (string concatenation) but add in a space: 或者,您可以按照自己的方式做(字符串串联),但要添加一个空格:

productName.Text = p.Make + " " + p.Model;

Use the string.concat method to concatenate string parts. 使用string.concat方法连接字符串部分。

productName.Text = string.concat(p.Make, " ", p.Model);

In general, you use the string.concat when you know you'll add less than a dozen parts. 通常,当您知道要添加的部分少于十二个时,可以使用string.concat More than that, or if you are in a loop, there is more benefits using the StringBuilder class. 除此之外,或者如果您处于循环中,则使用StringBuilder类有更多的好处。

productName.Text = p.Make  + " " + p.Model

Just concatenate a space between two words. 只需在两个单词之间连接一个空格。 I think this is the easiest way. 我认为这是最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM