26

I'm getting a string as a parameter.

Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the string.
E.g. if the passed string is 25 characters long, I want to add 5 more whitespaces.

The question is, how do I add whitespaces to a string?

Shashank Shekhar
  • 3,672
  • 2
  • 41
  • 50
user1765862
  • 12,589
  • 27
  • 102
  • 186
  • http://stackoverflow.com/questions/388461/how-can-i-pad-a-string-in-java – Lasse Espeholt Apr 06 '13 at 13:50
  • I think this question relates to the following post: http://stackoverflow.com/questions/10870037/how-to-add-certain-number-of-whitespaces-to-stringbuilder Greetings, – user2239197 Apr 06 '13 at 13:50

4 Answers4

52

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);
p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
D'Arcy Rittich
  • 160,735
  • 37
  • 279
  • 278
11

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.

Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
5

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                   "
Daniel Imms
  • 45,529
  • 17
  • 143
  • 160
4

you can use Padding in C#

eg

  string s = "Example";
  s=s.PadRight(30);

I hope It will resolve your problem.

Girish
  • 407
  • 2
  • 5
  • 18