C # - How can I format the output so that the line is always 7 digits long?
3 answers
Formatting like this $"{name, 7}"
ensures that the result is at least 7
; however, longer inputs will not be clipped (i.e. "Alexander"
will not be clipped to "Alexand"
).
We have to inject the logic manually, and I suggest hiding it in the extension method:
public static class StringExtensions {
public static string ToLength(this string source, int length) {
if (length < 0)
throw new ArgumentOutOfRangeException("length");
else if (length == 0)
return "";
else if (string.IsNullOrEmpty(source))
return new string(' ', length);
else if (source.Length < length)
return source.PadRight(length);
else
return source.Substring(0, length);
}
}
using:
Console.WriteLine($"{name1.ToLength(7)} {name2.ToLength(7)}");
+3
source to share
I would use an extension method in combination with PadRight()
public void Main() {
string name1 = "John";
string name2 = "Alexander";
string FullName = name1.FixLeft(7) + name2.FixLeft(7);
Console.WriteLine(FullName);
}
private static string FixLeft(this string TextInput, int DesiredLength) {
if (TextInput.Length < DesiredLength) { return TextInput.PadRight(DesiredLength); }
else { return TextInput.Substring(0,DesiredLength); }
}
+1
source to share