Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PadLeft doesn't work

Tags:

c#

.net

.net-4.0

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?

like image 649
Saeed Neamati Avatar asked Nov 27 '22 14:11

Saeed Neamati


2 Answers

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.

like image 61
zov Avatar answered Dec 11 '22 04:12

zov


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.

like image 29
Renatas M. Avatar answered Dec 11 '22 04:12

Renatas M.