Java輸出格式化之占位符


JAVA和C#在占位符方面有些區別,C#提供的占位符是用{num}這種形式,Java需要用%s這種形式,不太習慣,經查發現MessageFormat提供了花括號占位符的功能。

【轉自】https://blog.csdn.net/Mint6/article/details/78583316
在Java中貌似很少有占位符(placeholder)這個概念,取而代之的是fomat類,另外一些框架也實現了占位符這樣的東西。

在Java中有兩種占位符%和{},

%后面可以是d、f、s等中間也可以加其他參數。只能用於String類對象中,不能用於MessageFormat類對象。

{}中的數字要與后面的參數位置對應。只能用於MessageFormat類對象中,不能用於String類對象。

總的來說String.format()方法用起來不如MessageFormat.format()方法強大。

具體如何使用可以參考官方API文檔

http://docs.oracle.com/javase/7/docs/api/

下面的幾個例子僅供參考

import java.text.MessageFormat;
import java.util.Date;
 
public class test01 {
 
    public static void main(String[] args) {
        System.out.println("hello");// print hello
 
        // %s占位符,輸出字符串
        String username = "user1";
        int num = 3;
        System.out.printf("%s您好,您是第%s位訪客\n", username, num); // prints user1您好,您是第3位訪客
 
        // %f占位符
        double d = 1.2;
        float f = 1.2f;
        System.out.printf("%f %f", d, f); // prints 1.200000 1.200000
        
 
        // %1$s占位符
        //%n$ms:代表輸出的是字符串,n代表是第幾個參數,設置m的值可以在輸出之前放置空格,也可以設為0m,在輸出之前放置m個0 
        System.out.println(String.format("我是%1$s,我來自%2$s,今年%3$s歲", "中國人", "北京","22"));
        // prints 我是中國人,我來自北京,今年22歲
        
 
        // {}占位符,{}內的數字代表第幾個參數,參數從0開始
        String url = "www.baidu.com";
        int count = 1000;
        System.out.println(MessageFormat.format("該網站{0}被訪問了 {1} 次.", url, count));
        // prints 該網站www.baidu.com被訪問了 1,000 次.
 
 
        // {}占位符
        String template = "Welcome {0}!  Your last login was {1}";
        String output = MessageFormat.format(template, new Object[] { "Python",new Date().toString() });
        System.out.println(output);
        // prints  Welcome Python!  Your last login was Fri Oct 10 20:47:00 CST 2014
 
    }
 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM