Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
  } 
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...