PadLeft doesn't work
I'm trying to add a character many times before a string.开发者_高级运维 AMAIK in C#, it's PadLeft.
string firstName = "Mary";
firstName = firstName.PadLeft(3, '*'); // This should return ***Mary
But it doesn't work. Am I doing something wrong?
The first argument is total length of the returned string, as "Mary" is 4 characters long and your first argument is 3, it is working as expected. If you try firstName.PadLeft(6, '*')
you'll get **Mary.
You should add length of your string like that:
firstName = firstName.PadLeft(firstName.Length + 3, '*');
First parameter(totalWidth) represents the result string length. If your string length is less then totalWidth parameter, PadLeft adds so many chars that result string length will be equal to totalWidth.
No, it works. It will pad on the left with the supplied character to a total string length of 3. So, if you wanted a result of ***Mary
, you would have to use firstName.PadLeft(7, '*');
3 is the total length of the string so if your string is "a", it will become "**a"
see String.PadLeft Method (Int32, Char)
精彩评论