zoukankan      html  css  js  c++  java
  • java.String.format &Formatter

    o(∩_∩)o 

    String result = String.format("The format method is %s!", "great");
    // result now equals  "The format method is great!".

    You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.

    You will always use a % followed by some other characters to let the method know how it should display the string. %s is probably the most common, and it just means that the argument should be treated as a string.

    // we can specify the # of decimals we want to show for a floating point:
    String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
    // result now equals  "10 / 3 = 3.33"
    
    // we can add commas to long numbers:
    result = String.format("Today we processed %,d transactions.", 1000000);
    // result now equals  "Today we processed 1,000,000 transactions."

    String.format just uses a java.util.Formatter, so for a full description of the options you can see the Formatter javadocs.

    Instead of looking at the source code, you should read the javadoc String.format() and Formatter syntax

    String aString = "world";
    int aInt = 20;
    String.format("Hello, %s on line %d",  aString, aInt );

    To do what you tried ( use an argument index ) you use: n$

    String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
  • 相关阅读:
    学习笔记4
    学习笔记2
    学习笔记1
    树莓派与Arduino串口通信
    团队大作业第三周周报
    团队大作业第二周周报
    团队大作业第一周周报
    RTCSD_第三次作业
    RTCSD_第二次作业
    RTCSD_第一次作业
  • 原文地址:https://www.cnblogs.com/qiengo/p/2812677.html
Copyright © 2011-2022 走看看