-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);
  } 
} 
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's not why im searching. I want columns with a specific amount of characters. I know this simple formatting.
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.
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

5 Comments

But I want two or more columns side by side. And define for each columns the amount of characters.
I edit my answer, the %SomeNumber does it, like C#, please read the example i have put in the answer
Thanks, thats exactly what I have searched in Java
But can you also describe the different between %-10s and %10s? Would be great.
See documentation in the Flags section. The minus sign is used for left-alignment, the 10 is the padding width.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.