Formatting strings in C # to get the same spacing

I was looking for string formatting, and frankly, I got confused. This is what I want to do.

I have a "character statistics" page (this is a console application) and I want it to be formatted as follows:

=----------------------------------= = Strength: 24 | Agility: 30 = = Dexterity: 30 | Stamina: 28 = = Magic: 12 | Luck: 18 = =----------------------------------= 

I suppose I'm basically trying to figure out how to make this middle one '| the divider is in the same place, regardless of how many letters are status or how many points are stat.

Thanks for the input.

Edit: I also want the final '=' to also be in the same place.

+4
source share
4 answers

I learned something new, it seems! As some of the others have said, you can accomplish the same thing using String.Format .

The interpolation strings used in String.Format may also include an optional alignment component.

 // index alignment // vv String.Format("Hello {0,-10}!", "World"); 

If this is negative, the line is left-aligned. When it is positive, it is aligned to the right. In both cases, the line is filled with a space, respectively, if it is shorter than the specified width (otherwise the line is just completely inserted).

I believe this is a simpler and clearer method than having to mess with String.PadRight .


You can also use String.PadRight (or String.PadLeft ). Example:

 class Stats { // Contains properties as you defined ... } var stats = new Stats(...); int leftColWidth = 16; int rightColWidth = 13; var sb = new StringBuilder(); sb.AppendLine("=----------------------------------="); sb.Append("= "); sb.Append(("Strength: " + stats.Strength.ToString()).PadRight(leftColWidth)); sb.Append(" | "); sb.Append(("Agility: " + stats.Agility.ToString()).PadRight(rightColWidth)); // And so on. 
+12
source

I often used this technique in 80 games with text games. Obviously, at that time we did not have a line. but it allows you to visualize the layout in code.

Preformat the text the way you want to lay it out, and then just use the string.Format () function, for example ...

  string formattedText = @" =----------------------------------= = Strength: {0,2} | Agility: {3,2} = = Dexterity: {1,2} | Stamina: {4,2} = = Magic: {2,2} | Luck: {5,2} = =----------------------------------=".Trim(); string output = string.Format(formattedText, 12, 13, 14, 15, 16, 1); Console.WriteLine(output); Console.ReadLine(); 
+7
source
 String.Format("{0,-20}|","Dexterity: 30") 

will align the value to the left and place it up to 20 characters. The only problem is that if the parameter is longer than 20, it will not be truncated.

+4
source

You will need to use String.PadRight or String.PadLeft . Do something like this:

 Trip_Name1 = Trip_Name1.PadRight(20,' '); 

This is what you are looking for, I think.

+1
source

Source: https://habr.com/ru/post/1493033/


All Articles