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 );
  • 相关阅读:
    tcp粘包解决
    socket网络编程
    logging模块
    异常处理
    hashlib configparser模块
    列表推导式和生成器表达式和内置函数
    迭代器与生成器
    装饰器
    函数
    文件操作
  • 原文地址:https://www.cnblogs.com/qiengo/p/2812677.html
Copyright © 2011-2022 走看看