AnotherUser
AnotherUser

Reputation: 1353

What is an easy way to add n number of spaces to a string?

I would like to add n number of spaces to a string in C#.

I know this can be achieved with a for loop, but I was wondering if there was a nice one liner for it?

String newStr = "";
for(int i = numSpaces; i > 0; i--)
    newStr += " ";

Upvotes: 1

Views: 633

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283684

Since you want to add n spaces, not add spaces until the total length is n, you can use this String constructor:

newstr += new String(' ', numSpaces);

Upvotes: 2

OnoSendai
OnoSendai

Reputation: 3970

For N number of spaces, use this String constructor:

new string(' ', N)

Upvotes: 2

Related Questions