2

I have this code

String coNum = customerOrderLine.coNum.PadLeft(10 - customerOrderLine.coNum.Length);

I know that customerOrderLine.coNum = "123456" So I should end up with coNum being having 4 empty spaces at the front of it but I end up with it being "123456". How do I fix this? I tried PadRight in case that was the mistake and it also failed to work. I have to have the 4 empty spaces at the beginning to pass it into the API I am working on or it will fail.

1
  • Looks like it should work. Are you sure it's not padded? Display the string to make sure, and put delimiters around: "[" + coNum + "]"; Commented Dec 12, 2011 at 22:16

3 Answers 3

7

PadLeft takes a total length as a parameter, so I think you want

String coNum = customerOrderLine.coNum.PadLeft(10);
Sign up to request clarification or add additional context in comments.

1 Comment

Wow you are right. I totally didn't read the msdn page closely enough.
1

This is because you have incorrectly specified the totalWidth parameter of the Pad* method. From docs:

The number of characters in the resulting string, equal to the number of original characters plus any additional padding characters.[...] If totalWidth is equal to the length of this instance, the method returns a new string that is identical to this instance.

Comments

0

PadLeft does not specify a default character to pad with; your second argument should be the character to use for the pad, i.e.:

String coNum = customerOrderLine.coNum.PadLeft(10, ' ');

Edit: Also the first argument should be total desired length, not number of pad characters to add, per @Matthew's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.