开发者

Is there a neater way to insert a space between strings than something like " "?

When I write out a string combined with several strings (i.e. use stringbuilder or concat), I need to insert a space between each string. I'm often doing that like this:

StringBuilder sb = new StringBuilder();
sb.Append("a" + " " + "b");

Is there a more concise way of do开发者_JAVA百科ing the above?

Thanks


It's bizarre how many people just completely ignore the AppendFormat method on StringBuilder:

sb.AppendFormat("{0} {1}", str1, str2);


You can use String.Format method.

string test = String.Format("{0} {1} {2}", "part1", "part2", "part3");

Or in your case:

sb.AppendFormat("{0} {1}", a, b);


You could use the String.Join Method:

sb.Append(string.Join(" ", "a", "b"));

Note that this creates an intermediary string, which might be undesirable.


Less concise, but avoiding intermediary strings, would be something like this:

sb.Append("a").Append(' ').Append("b");


If you're after pure speed and efficient memory use I'd use...

sb.Append(str1);
sb.Append(" ");
sb.Append(str2);

For ease of reading, the example you give is clearer.

sb.Apend(str1+" "+str2);

The gain, however, will be negligable unless you're running this 1000s of times in a tight loop, so I'd go for the elegant, easy to read version (i.e. yours)


To literally answer your question of "is there a more concise way?" the answer is simple:

No.

If you want to specify an actual issue you're encountering, some code to illustrate it, then you will likely get more quality answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜