Reputation: 7513
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: 2233
Reputation: 108841
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
Reputation: 1039438
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
Reputation: 19230
You can use string.PadLeft
or string.PadRight
to pad your strings with a char, and string.Substring
to limit it.
Upvotes: 4