Gulbahar
Gulbahar

Reputation: 5537

Inserting formatting characters 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"))

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

Upvotes: 5

Views: 17401

Answers (4)

Michel de Ruiter
Michel de Ruiter

Reputation: 7954

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).

Upvotes: 0

LarsTech
LarsTech

Reputation: 81620

"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))

Upvotes: 11

Hand-E-Food
Hand-E-Food

Reputation: 12794

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 &.

Upvotes: 3

Martin
Martin

Reputation: 1448

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.

Upvotes: 2

Related Questions