Search code examples
c#paddingpadleft

PadLeft and PadRight using variables given in by user


I have a small problem using PadLeft and PadRight. So I have in my code that the user can input the character they want to use for padding and how many characters they wanna put in. Like this:

String StartString;
int AmountOfCharacters;
Char PadCharacter;

StartString = TextBoxString.Text(Lawnmower)
AmountOfCharacters = Convert.ToInt32(TextBoxAmountofCharacters.Text)    (Lets   Say 5)
PadCharacter = Convert.ToChar(TextBoxPadCharacter.Text)(Lets use *)

So then later i have put.

Padding = String.PadLeft(AmountOfCharacters,PadCharacter)

Now the problem I have when I run the code as I have it above it doesn't do anything. It just gives me as text lawnmower without any **** attatched. Do I have to change something in my code to make it work or am I using the wrong variables for this? Because when I use the PadCharacter as a String to I get a error message

Cannot implicitly convert String to char.


Solution

  • You misunderstand how PadLeft() works. The length you specify as a parameter (in your case AmountOfCharacters) does not specify how many characters you want added but how many characters the string should have at the end (at least).

    So when you specify the string "Lawnmower" and AmountOfCharacters = 5, nothing will happen because the word Lawnmower is already more than 5 characters long.