Link to home
Start Free TrialLog in
Avatar of kinton
kinton

asked on

Add blank spaces, limit spaces

Hi,

I am stumped with this one so any help would be greatly appreciated!

I am building an application to create files in asp.net, c#
I need to be able to enter a string then with a maximum of spaces eg, 20

say in the string i insert 'Education' i then need to pad after with 11 blank spaces.
if the string was 'School' i would need to pad after 14 blank spaces.

This is why pad.right(20) won't work as it will always add 20 spaces no matter what the string.

I have done something similar with numbers but can't work it out with this
*Numbers eg, [string noParcels = string.Format( "{0:d6}", parcels + 1 );] allows max 6 numbers, padding to the left with 0's after number entered.
Avatar of mohan_sekar
mohan_sekar
Flag of United States of America image

Say, you always want your string to be 5 chars wide
pageNo = "00000" + pageNo
Right(pageNo, 5)

if pageNo is '1', then the above will return 00001.
Is this what you are looking for?
ASKER CERTIFIED SOLUTION
Avatar of copyPasteGhost
copyPasteGhost
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi,

str.PadRight(20) add spaces so you would get spaces padded up to 20 chars. It doesn't limit a string to 20 chars though.

"test".PadRight(20);  would give you "test                "
and

"testtest".PadRight(20);  would give you "testtest            "

/peter
Avatar of kinton
kinton

ASKER

Hi thanks for your quick response.

What is this Right?
It doesn't pick up on my intellisense and is read as an error.

here is the line in my code
Avatar of kinton

ASKER

sorry didnt see the other solutions, let me just check
PadRight is a string method.

"This is why pad.right(20) won't work as it will always add 20 spaces no matter what the string."

No it doesn't http://msdn.microsoft.com/en-us/library/34d75d7s.aspx

yourstring = yourotherString.PadRight(20)

should be fine.


If you also want to handle strings that are too long.

yourstring = String.SubString(yourotherString.PadRight(20), 0, 20);

If you put a breakpoint on my example you will see it will give you the results you want.

Ghost
Avatar of kinton

ASKER

Ok this solution does work great! many thanks!
Thanks for the points.