Home >Java >javaTutorial >How to quickly align in java

How to quickly align in java

下次还敢
下次还敢Original
2024-04-21 02:33:44631browse

Methods to achieve text alignment in Java include: using the String.format() method to specify the alignment, text width and type; using the DecimalFormat class to format and align numbers; using StringBuilder to dynamically splice text and Control alignment.

How to quickly align in java

Quickly align text in Java

Method 1: String.format()

Use the String.format() method to quickly align text. The format is as follows:

<code class="java">String.format("%<flags><width>.<precision>[type]string", object)</code>

where:

  • ##: Specify the alignment, such as - (left-aligned) or (right-aligned)
  • : Specify Minimum width of text
  • <code>: Specifies the number of digits after the decimal point (only applicable to numeric types)</code> </li> <li>[type]<code>: Optional type specifier such as </code>d<code> (integer) or </code>s<code> (string) </code> </li> <li>string<code>: The string to align </code> </li> </ul> <p>Example: <strong></strong></p> <pre class="brush:php;toolbar:false"><code class="java">String s = String.format("%-20s", "Hello World"); System.out.println(s); // 输出:Hello World (左对齐,总宽度为 20)</code>

    Method 2: DecimalFormat

    For numbers, you can use

    DecimalFormat Class to format and align text.

    Example:

    <code class="java">DecimalFormat df = new DecimalFormat("#,###.##");
    String s = df.format(123456.789);
    System.out.println(s); // 输出:123,456.79 (右对齐,小数点后保留两位)</code>

    Method 3: StringBuilder

    For situations where dynamic splicing of text is required, you can use

    StringBuilder.

    Example:

    <code class="java">StringBuilder sb = new StringBuilder();
    sb.append("Hello").append(" ").append("World");
    String s = sb.toString();
    System.out.println(s); // 输出:Hello World</code>

    The above is the detailed content of How to quickly align in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn