C # - How can I format the output so that the line is always 7 digits long?
string name1 = "John";
string name2 = "Alexander";
Console.WriteLine(??);
//desired output:
John Alexand
How can I format the lines so that they always take up 7 spaces? I know how to do it in C, but I can't seem to find a way to do it for C #.
Use PadRight
andSubString
var a = "James";
Console.WriteLine(a.PadRight(7, ' ').Substring(0, 7));
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)}");
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); }
}