Java字符串format()方法使用給定的語言環境,指定的格式字符串和參數返回格式化的字符串。我們可以使用此方法來連接字符串,同時可以格式化輸出的連接字符串。
簽名:
字符串format()方法有兩種類型:
public static String format(Locale loc, String form, Object… args)
and,
public static String format(String form, Object… args)
參數:
- loc-應用於format()方法的語言環境值
form-輸出字符串的格式
args-它指定格式字符串的參數數目。它可以是零或更多。
返回:
This method returns a formatted string.
異常:
-
NullPointerException -如果格式為null。
IllegalFormatException-如果指定的格式不合法或參數不足。
例:展示format()方法的用法原理
// Java program to demonstrate
// working of format() method
class Gfg1 {
public static void main(String args[])
{
String str = "GeeksforGeeks.";
// Concatenation of two strings
String gfg1 = String.format("My Company name is %s", str);
// Output is given upto 8 decimal places
String str2 = String.format("My answer is %.8f", 47.65734);
// between "My answer is" and "47.65734000" there are 15 spaces
String str3 = String.format("My answer is %15.8f", 47.65734);
System.out.println(gfg1);
System.out.println(str2);
System.out.println(str3);
}
}
輸出:
My Company name is GeeksforGeeks. My answer is 47.65734000 My answer is 47.65734000
// Java program to demonstrate
// concatenation of arguments to the string
// using format() method
class Gfg2 {
public static void main(String args[])
{
String str1 = "GFG";
String str2 = "GeeksforGeeks";
//%1$ represents first argument, %2$ second argument
String gfg2 = String.format("My Company name" +
" is:%1$s, %1$s and %2$s", str1, str2);
System.out.println(gfg2);
}
}
輸出:
My Company name is:GFG, GFG and GeeksforGeeks
// Java program to show
// left padding using
// format() method
class Gfg3 {
public static void main(String args[])
{
int num = 7044;
// Output is 3 zero's("000") + "7044",
// in total 7 digits
String gfg3 = String.format("%07d", num);
System.out.println(gfg3);
}
}
輸出:
0007044
相關用法
- Java PrintWriter format(String, Object)用法及代碼示例
- Java PrintStream format(String, Object)用法及代碼示例
- Java PrintStream format(Locale, String, Object)用法及代碼示例
- Java PrintWriter format(Locale, String, Object)用法及代碼示例
- Java ChronoLocalDateTime format()用法及代碼示例
- Java ZonedDateTime format()用法及代碼示例
- Java ChronoZonedDateTime format()用法及代碼示例
- Java MonthDay format()用法及代碼示例
- Java LocalTime format()用法及代碼示例
- Java ChronoLocalDate format()用法及代碼示例
- Java DateFormat format()用法及代碼示例
- Java SimpleDateFormat format()用法及代碼示例
- Java OffsetDateTime format()用法及代碼示例
- Java Year format()用法及代碼示例
- Java ChoiceFormat format()用法及代碼示例
注:本文由純淨天空篩選整理自Niraj_Pandey大神的英文原創作品 Java String format() with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。