400_the_cat
400_the_cat

Reputation: 883

String.Format line break

i have a simple statement of code that reads:

Return String.Format("{0} {1} {2}", _var1, _var2, _var3)

i'm trying to get this formatted string to output each var on it's own line. i'm new to vb.net but i did try one thing:

"{0}\n {1}\n {2}"

that didn't work. any help?

Upvotes: 11

Views: 21509

Answers (7)

Wolfgang Grinfeld
Wolfgang Grinfeld

Reputation: 1008

Simplest solution:

return $"{_var1}
{_var2}
{_var3}"

Or alternatively:

return $"{_var1}{vbCrlf}{_var2}{vbCrlf}{_var3}"

Do ensure that you are on one of the more current VB implementations.

Upvotes: 0

Jeff Reed
Jeff Reed

Reputation: 231

Function sformat([string], ParamArray args()) As String
    [string] = [string].replace("\n", vbLf)
    [string] = [string].replace("\r", vbCr)
    Return String.Format([string], args)
End Function

use like you would use string.format except call sformat(yourstring, param1, param2)

Upvotes: 1

Darrel Lee
Darrel Lee

Reputation: 2460

This also works using xml literal for the format string

        Dim fmt = _
<xml>Var 1: {0}
Var 2: {1}
Var 3: {2}</xml>
        Trace.WriteLine(String.Format(fmt.Value, 1, 2, 3))

Upvotes: 0

Darrel Lee
Darrel Lee

Reputation: 2460

OK So VB is lame in this regard. How about this:

String.Format("Var1: {0}\nVar2: {1}\nVar3: {2}".Replace("\n", vbCrLf), var1, var2, var3)

Upvotes: 0

DaveR
DaveR

Reputation: 91

I'd use something like

String.Format("{1}{0},{2}{0},{3}{0}", vbcrlf, _var1, _var2, var2)

Upvotes: 2

knslyr
knslyr

Reputation: 640

I would go with something like this:

Return String.Format("{0}{1}{2}",_var1 & vbcrlf, _var2 & vbcrlf, _var3 & vbcrlf)

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128317

How about this:

Return String.Format( _
    "{1}{0}{2}{0}{3}{0}", _
    Environment.NewLine, _
    _var1, _
    _var2, _
    _var3 _
)

This could work too, though it's a bit "trickier":

Return New StringBuilder() _
    .AppendLine(_var1.ToString()) _
    .AppendLine(_var2.ToString()) _
    .AppendLine(_var3.ToString()) _
    .ToString()

Upvotes: 22

Related Questions