Saphire
Saphire

Reputation: 1930

Format text by adding whitespace

I am trying to format strings by whitespaces. All strings normally look like

01. Anton 30p
02. Cinderella 20p
03. Thomas 18p
04. Anastacia-Laura 16p

I want to format each string, that the points start at the same column. There I wrote:

s = stringUpToName;
int addSpacing = 37 - s.Length;
for (int i = 0; i < addSpacing; i += 1) s += " ";

s += points;

It gets closer this way, but it's still not perfectly formatted.

I want it to look like this:

01. Anton            30p
02. Cinderella       20p
03. Thomas           18p
04. Anastacia-Laura  16p

Upvotes: 2

Views: 1350

Answers (3)

John Jesus
John Jesus

Reputation: 2404

Try right-align the numbers using

String.Format("{0} {1} {2,4}p", Num, Name, Point);

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Use "0" custom specifier as zero-placeholder symbol to format index/number of record. 0:00 will give you 01 for value 1.

Also keep in mind that item format syntax is { index[,alignment][:formatString]} where alignment indicates preferred formatted field width. So, adding alignment to second item format {1,20} gives you right-aligned field width of 20 characters. With negative alignment field will be left-aligned.

Total format string will look like "{0:00}. {1,-20}{2}p"

You can use it with String.Format or StringBuilder.AppendFormat if you are build string, or Console.WriteLine if you are writing it to console.

int index = 1;
string name = "Anton";
int points = 30;
var result = String.Format("{0:00}. {1,-20}{2}p", index, name, points)
// "01. Anton               30p"

Upvotes: 4

Steve
Steve

Reputation: 216293

String.Format and Composite Formatting using the Alignment functionality

string[] names = new string[]
{
    "1. Anton 30p",
    "2. Cinderella 20p",
    "3. Thomas 18p",
    "4. Anastacia-Laura 16p"
};

foreach(string s in names)
{
    int lastSpace = s.LastIndexOf(' ');
    int firstSpace = s.IndexOf(' ');
    string result = string.Format("{0,-4}{1,-37}{2,4}", s.Substring(0, firstSpace), s.Substring(firstSpace + 1, lastSpace), s.Substring(lastSpace+1));
    Console.WriteLine(result);

}

Keep in mind that to see the output exactly aligned in columns you need to use a Fixed Width font like Lucida Console or Courier, because fonts with variable width use less pixel to print an I than to print a W.

Upvotes: 0

Related Questions