PadLeft does not work

I try to add a character many times before a string. AMAIK in C #, this is PadLeft.

string firstName = "Mary"; firstName = firstName.PadLeft(3, '*'); // This should return ***Mary 

But that will not work. Am I doing something wrong?

+4
source share
4 answers

The first argument is the total length of the returned string, since "Mary" has a length of 4 characters, and your first argument is 3, it works as expected. If you try firstName.PadLeft (6, '*') you will get ** Mary

+16
source

You should add the length of your string as follows:

 firstName = firstName.PadLeft(firstName.Length + 3, '*'); 

The first parameter (totalWidth) represents the length of the result string. If the line length is less than the totalWidth parameter, PadLeft adds so many characters that the total line length will be equal to totalWidth.

+4
source

No, it works. It will put on the left with the provided character the total length of line 3. So, if you want the result ***Mary , you will need to use firstName.PadLeft(7, '*');

+3
source

3 is the total length of the string, so if your string is "a", it will become "** a"

see String.PadLeft Method (Int32, Char)

+2
source

All Articles