Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting String Length Limit then either substring or space filled

Tags:

string

c#

vb.net

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

like image 836
Gage Avatar asked Mar 02 '26 10:03

Gage


2 Answers

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  '
like image 137
Darin Dimitrov Avatar answered Mar 04 '26 23:03

Darin Dimitrov


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

like image 28
TheCodeKing Avatar answered Mar 05 '26 00:03

TheCodeKing