How to convert a string to a fixed lenght string?

Y

ywchan

I would like to convert a string to a fixed length
e.g. if fixed length = 10
'abc' -> ' abc'
'abcdefghijklm' -> 'abcdefghij'

Is there any simple function in C# can perform this operation?
thanks!
 
M

Morten Wennevik

Hi ywchar,

You can use PadLeft and SubString to first add space characters if needed, then chop of anything above 10 characters.

string s = mystring.PadLeft(10, ' ').SubString(0, 10);
 
S

scott

int fixedLength = 10;

string aString = "abcdefghijklm";



if (aString.Length >= fixedLength)

{

aString =
aString.Substring(0,fixedLength);

}

the substring function takes 2 values. the first is where you want to start
in the string. the second is the length of the string to where you want to
go to. So in this case we start at the beggining of the string (0) and we
want to go 10 along. A new string is returnd that is a length of 10, the
rest have been cut off.
 
J

James Curran

Morten said:
You can use PadLeft and SubString to first add space characters if
needed, then chop of anything above 10 characters.
string s = mystring.PadLeft(10, ' ').SubString(0, 10);

Um... That will always give you just 10 space in the string. The best
one-liner I could come up with is:

string s = mystring.PadLeft(10, ' ').SubString(mystring.Length > 9 ? 10 :
mystring.Length, 10);

The trick is that the padding it on the left, but the truncation is on the
right.

Usually, both padding & truncation is on the right, in which case, a minor
varaition on yours would work:

string s = mystring.PadRight(10, ' ').SubString(0, 10);
 
M

Morten Wennevik

Sorry, I'm not following.

Padding occurs only if the string is less than 10 characters, and to the left of the text as he specified. If padding is necessary, substring will be ignored as the string will be exactly 10 characters.
 
J

James Curran

ooops... I guess I should have look up what PadLeft actually does. I
was assuming that it would always add exactly 10 spaces.

--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

Morten Wennevik said:
Sorry, I'm not following.

Padding occurs only if the string is less than 10 characters, and to the
left of the text as he specified. If padding is necessary, substring will
be ignored as the string will be exactly 10 characters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top