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.
LVL 2
kintonAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
copyPasteGhostConnect With a Mentor Commented:
This works...

int NumberOfSpaces = 20;
      string test = "Education";
      if (test.Length >= NumberOfSpaces) {
         test = test.Substring(0, NumberOfSpaces);
      }
      else {
         test = test.PadRight(NumberOfSpaces, ' ');
      }
0
 
mohan_sekarCommented:
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?
0
 
pivarCommented:
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
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
kintonAuthor Commented:
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
0
 
kintonAuthor Commented:
sorry didnt see the other solutions, let me just check
0
 
copyPasteGhostCommented:
PadRight is a string method.
0
 
gregoryyoungCommented:

"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);

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

Ghost
0
 
kintonAuthor Commented:
Ok this solution does work great! many thanks!
0
 
copyPasteGhostCommented:
Thanks for the points.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.