Adding whitespaces to a string in C#

You can use String.PadRight for this.

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

For example:

string paddedParam = param.PadRight(30);

You can use String.PadRight method for this;

Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.

string s = "cat".PadRight(10);
string s2 = "poodle".PadRight(10);

Console.Write(s);
Console.WriteLine("feline");
Console.Write(s2);
Console.WriteLine("canine");

Output will be;

cat       feline
poodle    canine

Here is a DEMO.

PadRight adds spaces to the right of strings. It makes text easier to read or store in databases. Padding a string adds whitespace or other characters to the beginning or end. PadRight supports any character for padding, not just a space.


Use String.PadRight which will space out a string so it is as long as the int provided.

var str = "hello world";
var padded = str.PadRight(30);
// padded = "hello world                   "

Tags:

C#

String