开发者

Inserting formatting characters in String.Format?

开发者 https://www.devze.com 2023-03-28 11:54 出处:网络
I googled for this, but VB.Net (2008) doesn\'t seem to allow inserting formatting characters (eg. \\t, \\r\\n) in String.Format:

I googled for this, but VB.Net (2008) doesn't seem to allow inserting formatting characters (eg. \t, \r\n) in String.Format:

'BAD MessageBox.Show(String.Format("{0}{tab}{1}", "Foo", "Bar"))
'BAD MessageBox.Show(String.Format("{0}\t{1}", "Foo", "Bar"))
MessageBox.Show(String.Format("{0}" & vbTab & "{1}", "Foo", "Bar"))
开发者_StackOverflow

Is there an easier way to build a formatted string that must contain formatting characters?


"Easier" is probably in the eye of the beholder, but here is a different way:

MessageBox.Show(String.Join(vbTab, {"Foo", "Bar"}))

I also came up with this:

MessageBox.Show(String.Format("{0}\t{1}\t{2}", "Foo", "Bar", "Test").Replace("\t", vbTab))


Using vbTab works fine (and vbCrLf etc also).

\t \n etc is fior C, not VB

{tab} is a code for SendKeys

I conclude that your 3rd line is the (only) working method unless something like this

MessageBox.Show("Foo" & vbTab & "Bar")

is possible: it reads easier I guess.


I suppose another option is:

String.Format("{1}{0}{2}{0}{3}{0}{4}", vbTab, "Foo", "Bar", "was", "here")

Not the most readable, but better than & vbTab &.


Recent versions support interpolated strings to simplify it to this:

MessageBox.Show(String.Format($"{{0}}{vbTab}{{1}}", "Foo", "Bar"))

Or just:

MessageBox.Show($"{"Foo"}{vbTab}{"Bar"}")

Note the $ before the first " (and duplicated braces in the first version).

0

精彩评论

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