-1

Is there a native code or library in Java for formatting a String like in the way below made in C#?

Source: Format a string into columns (C#)

public string DropDownDisplay { 
  get { 
    return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"), 
                          Name, City, State, ID);
  } 
} 
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
FanaticTyp
  • 195
  • 4
  • 15

3 Answers3

4

Java provides String.format() with various options to format both text and numbers.

There is no need for additional libraries, it is a built-in feature.

The syntax is very similar to your example. Basically, to print a String, you can use the %s placeholder. For decimal numbers, use %d. See my link above to get a full list of all possible types.

String name = "Saskia";
int age = 23;
String formattedText = String.format("%s is %d years old.", name, age);

You can add flags for additional padding and alignment, if you want a column-like output.

String formattedText = String.format("%-10s is %-5d years old.", name, age);

In %-10s the %s defines the type String, the - is used for left-alignment and the 10 defines the width of the padding.

user1438038
  • 5,821
  • 6
  • 60
  • 94
  • That's not why im searching. I want columns with a specific amount of characters. I know this simple formatting. – FanaticTyp Jan 19 '18 at 10:14
  • I have updated my anser and included information about formatting flags. See my link, there is a whole section on those flags in the documentation. – user1438038 Jan 19 '18 at 10:19
3

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

Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
1

The simple String method format provides the same as C's printf.

But the JDK class java.text.MessageFormat provides a very rich set of ways for formatting.

laune
  • 31,114
  • 3
  • 29
  • 42