简体   繁体   中英

String interpolation - repeat

Is there any way to interpolate variable several times without repeating?

For example:

var name = "bla";
Console.WriteLine($"foo {name:repeat:2} bar")

to print

foo blabla bar

I'm particularly interested in interpolating several line breaks instead of repeating {Environment.NewLine} several times in the interpolation mask like this:

$"{Environment.NewLine}{Environment.NewLine}"
public static string Repeat(this string s, int times, string separator = "")
{
    return string.Join(separator, Enumerable.Repeat(s, times));
}

Then use:

Console.WriteLine($"foo {name.Repeat(2)} bar")

You could write an extension method for the string type, thats repeating its input. Then simply use this method within the curly braces.

You could also use

var name = "bla";
Console.WriteLine("foo {0}{0} bar", name);
// or
var s = String.Format("foo {0}{0} bar", name);

It will help you not repeating the same string, just index of it.

More about String Format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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