Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#- How can I format an output so that a string always takes up 7 digits?

Tags:

string

c#

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#.

like image 480
Frank Anderson Avatar asked Jan 19 '26 17:01

Frank Anderson


2 Answers

Use PadRight and SubString

var a = "James";
Console.WriteLine(a.PadRight(7, ' ').Substring(0, 7));
like image 106
anish Avatar answered Jan 21 '26 06:01

anish


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)}");
like image 32
Dmitry Bychenko Avatar answered Jan 21 '26 06:01

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!