Home >> Blog >> Java String format 方法及範例

在執行SEO搜尋引擎優化過程中我們常常會遇到要處理java相關的一些語法,今天就來聊聊Java String format 方法及範例。

Java String format 方法及範例

在 java 中,String format() 方法使用給定的語言環境、指定的格式字符串和參數返回一個格式化的字符串。我們可以使用這種方法連接字符串,同時我們可以格式化輸出的連接字符串。

語法:有兩種類型的字符串 format()方法

public static String format(Locale loc, String form, Object... args)

public static String format(String form, Object... args)

範圍:

  • 要應用於 format() 方法的語言環境值
  • 輸出字符串的格式。
  • args 指定格式字符串的參數數量。它可能為零或更多。

返回類型:格式化字符串。

拋出異常:

  • NullPointerException: 如果格式為空。
  • IllegalFormatException: 如果指定的格式非法或參數不足。

範例 1:

// Java program to demonstrate
// working of format() method

// Main class
class GFG {

// MAin driver method
public static void main(String args[])
{
// Custom input string to be formatted
String str = "GeeksforGeeks";

// Concatenation of two strings
String s = 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);

// Here answer is supposed to be %15.8f" and
// "47.65734000" there are 15 spaces
String str3 = String.format("My answer is %15.8f",
47.65734);

// Print and display strings
System.out.println(s);
System.out.println(str2);
System.out.println(str3);
}
}

輸出

My Company name is GeeksforGeeks
My answer is 47.65734000
My answer is 47.65734000

範例 2:

// Java program to demonstrate Concatenation of Arguments
// to the string using format() method

// Main class
class GFG {

// Main driver method
public static void main(String args[])
{
// Custom input string to be formatted
String str1 = "GFG";
String str2 = "GeeksforGeeks";

// %1$ represents first argument
// %2$ second argument
String str = String.format(
"My Company name"
+ " is: %1$s, %1$s and %2$s",
str1, str2);

// Print and display the formatted string
System.out.println(str);
}
}

輸出:

My Company name is: GFG, GFG and GeeksforGeeks

範例 3:

// Java program to Illustrate Left Padding
// using format() method

// Main class
class GFG {

// Main driver method
public static void main(String args[])
{
// Custom integer number
int num = 7044;

// Output is 3 zero's("000") + "7044",
// in total 7 digits
String str = String.format("%07d", num);

// Print and display the formatted string
System.out.println(str);
}
}

輸出:

0007044