Kimi
Kimi

Reputation: 563

Adding a fixed number of spaces to the end of a variable length string

I have a string say message, whose length is not variable. But whatever the length is, I have to add 35 spaces to it before starting another method.

Suggestions Please?

Thanks!

Ex - String = "abc" , should become "abc" + 35 spaces;

No matter what the string is, I need to "Append" 35 spaces to the end of the string.

Upvotes: 7

Views: 17181

Answers (4)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

This should do the trick:

message = message.PadRight(message.Length + 35, ' ');

Upvotes: 16

user1693593
user1693593

Reputation:

In order to pad a string in C# and VB.net, can use the PadRight method of the String object:

It has two overloads:

String.PadRight(Int32 NumOfChars)
String.PadRight(Int32 NumOfChars, char Char)

F.ex:

string myString = "abc".PadRight(numOfChars, charToPadWith);

or

myString = myString.PadRight(numOfChars, charToPadWith);

For documentation:
http://msdn.microsoft.com/en-us/library/system.string.padright.aspx

Upvotes: 3

Nicodemeus
Nicodemeus

Reputation: 4083

string paddedValue = string.Format("ABC{0}", new String(" ", 35));

Upvotes: 3

D Stanley
D Stanley

Reputation: 152566

string s = "abc";
s += new string(' ', 35);

Upvotes: 6

Related Questions