Is there a one-liner way of setting a string
to a fixed length (in C#), either by truncating it or padding it with spaces (' '
).
For example:
string s1 = "abcdef";
string s2 = "abc";
after setting both to length 5
, we should have:
"abcde"
"abc "
For 'C' there is alternative (more complex) use of [s]printf that does not require any malloc() or pre-formatting, when custom padding is desired. The trick is to use '*' length specifiers (min and max) for %s, plus a string filled with your padding character to the maximum potential length.
To truncate a string in C, you can simply insert a terminating null character in the desired position. All of the standard functions will then treat the string as having the new length.
Padding in string is adding a space or other character at the beginning or end of a string. String class has String. PadLeft() and String. PadRight() methods to pad strings in left and right sides. Padding in string is adding a space or other character at the beginning or end of a string.
What is the max string length in C#? The maximum string length in C# is 2^31 characters. That's because String. Length is a 32-bit integer.
All you need is PadRight
followed by Substring
(providing that source
is not null
):
string source = ...
int length = 5;
string result = source.PadRight(length).Substring(0, length);
In case source
can be null
:
string result = source == null
? new string(' ', length)
: source.PadRight(length).Substring(0, length);
private string fixedLength(string input, int length){
if(input.Length > length)
return input.Substring(0,length);
else
return input.PadRight(length, ' ');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With