string name1 = "John";
string name2 = "Alexander";
Console.WriteLine(??);
//desired output:
John Alexand
How can I format the strings so that they will always take up 7 spaces? I'm familiar with how to do this in C, but I cannot find a way to do it for C#.
Use PadRight and SubString
var a = "James";
Console.WriteLine(a.PadRight(7, ' ').Substring(0, 7));
Formatting like $"{name, 7}" ensures that the result will have length at least 7; however, longer inputs will not be trimmed (i.e. "Alexander" will not be trimmed to "Alexand").
We have to impement the logic manually and I suggest hiding it in an 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);
}
}
usage:
Console.WriteLine($"{name1.ToLength(7)} {name2.ToLength(7)}");
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