Gage
Gage

Reputation: 7483

Setting String Length Limit then either substring or space filled

Scenario: I'm creating a file thats need to be in this format https://www.rbcroyalbank.com/ach/file-451771.pdf . I need to be able to set the limit of the string length for certain fields.

Question: Is there an easy way to set the limit of the field so that if the string was larger then the limit then just take the substring and if smaller would add extra spaces?

Note: I was able to accomplish something similar to this with integers by just using .toString("00000").

Upvotes: 2

Views: 2224

Answers (3)

O. Jones
O. Jones

Reputation: 108641

This is straightforward.

const int MaxStringLength = 100;  /* set to your maximum length */
...
myString = (myString.Length >= MaxStringLength)
            ? myString.Substring(0, MaxStringLength)
            : myString.PadRight(MaxStringLength);

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could use the PadRight in conjunction with the Substring methods (where 5 could of course be variablized according to your needs):

Console.WriteLine("'{0}'", "abcdefgh".PadRight(5).Substring(0, 5));
Console.WriteLine("'{0}'", "abc".PadRight(5).Substring(0, 5));

prints:

'abcde'
'abc  '

Upvotes: 9

TheCodeKing
TheCodeKing

Reputation: 19220

You can use string.PadLeft or string.PadRight to pad your strings with a char, and string.Substring to limit it.

Upvotes: 4

Related Questions