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 "
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, ' ');
}
I would use the @waka answer, but as an extension method and null verification, like this:
public static string FixedLength(this string value, int totalWidth, char paddingChar)
{
if (value is null)
return new string(paddingChar, totalWidth);
if (value.Length > totalWidth)
return value.Substring(0, totalWidth);
else
return value.PadRight(totalWidth, paddingChar);
}