Format a String into Columns

Format a string into columns

You can specify the number of columns occupied by the text as well as alignment using Console.WriteLine or using String.Format:

// Prints "--123       --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "-- 123--"
Console.WriteLine("--{0,10}--", 123);

The number specifies the number of columns you want to use and the sign specifies alignment (- for left alignment, + for right alignment). So, if you know the number of columns available, you could write for example something like this:

public string DropDownDisplay { 
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}

If you'd like to calculate the number of columns based on the entire list (e.g. the longest name), then you'll need to get that number in advance and pass it as a parameter to your DropDownDisplay - there is no way to do this automatically.

Formatting a string into columns using String Interpolation

You can use Alignment Component for this purpose. Like this:

Console.WriteLine($"value: {d,-17} {s}");

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

So this is why we use negative alignment because you want the first column be left-aligned.

String formatting: Columns in line

str.format() is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

'>' Forces the field to be right-aligned within the
available space (this is the default for numbers).

'=' Forces the padding to be placed after the
sign (if any) but before the digits. This is used for printing fields
in the form ‘+000000120’. This alignment option is only valid for
numeric types.

'^' Forces the field to be centered within the
available space.

Here's an example (with both left and right alignments):

>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')):
... print '{0:<10} {1:>8} {2:>8}'.format(*args)
...
apple $1.09 80
truffle $58.01 2

How to format string output, so that columns are evenly centered?

I'm also going with the "format" suggestion, but mine is a little different.

In your program, you're relying on your card's toString. So make that formatted in a fixed length, and then you can use them anywhere and they will take up the same space.

public String toString() {
return String.format( "%5s of %-8s", rank, suit );
}

When you print this out, you'll have all your cards aligned on the "of" part, which I think is what you were going for in your first output column.

The "%5s" part right-aligns the rank in a field 5 characters wide, and the "%-8s" part left-aligns the suit in a field 8 characters wide (which means there are additional spaces to the right if the suit is shorter than 8 characters).

Aligning strings into columns

You can divide the total line width by the number of columns and pad each string to that length. You may also want to trim extra long strings. Here's an example that pads strings that are shorter than the column width and trims strings that are longer. You may want to tweak the behavior for longer strings:

    int Columns = 4;
int LineLength = 80;

public void WriteGroup(String[] group)
{
// determine the column width given the number of columns and the line width
int columnWidth = LineLength / Columns;

for (int i = 0; i < group.Length; i++)
{
if (i > 0 && i % Columns == 0)
{ // Finished a complete line; write a new-line to start on the next one
Console.WriteLine();
}
if (group[i].Length > columnWidth)
{ // This word is too long; truncate it to the column width
Console.WriteLine(group[i].Substring(0, columnWidth));
}
else
{ // Write out the word with spaces padding it to fill the column width
Console.Write(group[i].PadRight(columnWidth));
}
}
}

If you call the above method with this sample code:

var groupOfWords = new String[] { "alphabet", "alegator", "ant", 
"ardvark", "ark", "all", "amp", "ally", "alley" };
WriteGroup(groupOfWords);

Then you should get output that looks like this:

alphabet            alegator            ant                 ardvark
ark all amp ally
alley

Java String Formatting (Columns)

Java also have a String formatting option :

public String DropDownDisplay(){
return String.format("%-10s - %-10s, %10s - %5s", "name", "city", "state", "id");
}

There many format specifiers as :

  • %s - String value
  • %d - Decimal integer

For specifying a width you can use the %SomeNumber option,

positive number will Right-justify within the specified width, and a negative number will be Left-Justify.

Here is Java format examples that you can use



Related Topics



Leave a reply



Submit