روش جاوا string.format() چیست؟
متد فرمت رشته جاوا () برای قالب بندی رشته ها، اعداد صحیح، مقادیر اعشاری و غیره با استفاده از مشخص کننده های فرمت مختلف استفاده می شود. این متد رشته فرمت شده را با استفاده از محل داده شده، فرمت کننده مشخص شده و آرگومان ها برمی گرداند. اگر محلی ارائه نشده باشد، از محلی پیش فرض برای قالب بندی رشته ها استفاده می کند. string.format () متد استاتیک کلاس جاوا String است .
public static String format(Locale loc, String format, Object… args)
public static String format(String format, Object… args)
مولفه های
- مقدار محلی که در متد ()format اعمال خواهد شد .
- تعیین فرمت رشته خروجی
- تعداد آرگومان های رشته فرمت از 0 تا چندین متغیر است.
- NullPointerException ، اگر قالب null باشد، NullPointerException پرتاب می شود.
- IllegalFormatException ، اگر قالب مشخص شده غیرقانونی باشد، یا آرگومان های کافی ارائه نشده باشد، این استثنا پرتاب می شود.
تعیین کننده های قالب
بیایید به برخی از مشخص کننده های رایج نگاه کنیم.مشخص کننده | شرح |
---|---|
%s، %S | یک فرمت کننده رشته |
%d | یک عدد صحیح اعشاری که فقط برای اعداد صحیح استفاده می شود. |
%o | یک عدد صحیح هشتگانه که فقط برای اعداد صحیح استفاده می شود. |
%f، %F | برای اعداد اعشاری، برای اعداد ممیز شناور استفاده می شود. |
%x، %X | یک عدد صحیح هگزادسیمال که فقط برای اعداد صحیح استفاده می شود. |
مثال های روش جاوا String.format().
class Main {
public static void main(String[] args) {
// Integer value
System.out.println(String.format("%d", 234));
// String value
System.out.println(String.format("%s", "format() method"));
// Float value
System.out.println(String.format("%f", 99.99));
// Hexadecimal value
System.out.println(String.format("%x", 99));
// Char value
System.out.println(String.format("%c", 'f'));
// Octal value
System.out.println(String.format("%o", 99));
}
}
خروجی
روش 234 format() 99.990000 63 f 143
مثال
class Main {
public static void main(String[] args) {
int n1 = 99;
// using two different specifiers for formatting the string
System.out.println(String.format("%s\nhexadecimal: %x", "Result is", n1));
}
}
خروجی
نتیجه هگزادسیمال است: 63
مثال
// to use Locale
import java.util.Locale;
class Main {
public static void main(String[] args) {
int number = 9999999;
// using the default locale if none specified
System.out.println(String.format("Number: %,d", number););
// using the GERMAN locale as the first argument
System.out.println(String.format(Locale.GERMAN, "Number in German: %,d", number));
}
}
خروجی
شماره: 9,999,999 شماره در آلمانی: 9.999.999
GO TO FULL VERSION