자바에서는 문자열 형식() 메서드 주어진 문자열을 사용하여 형식화된 문자열을 반환합니다. 현지의 , 지정됨 형식 문자열 , 그리고 인수 . 이 방법을 사용하여 문자열을 연결할 수 있으며 동시에 연결된 문자열 출력의 형식을 지정할 수 있습니다.
문자열 형식()의 구문
두 가지 유형이 있습니다. 문자열 형식() 아래에 언급된 방법:
public static String format (Locale loc , String form , Object... args ) public static String format (String form , Object... args )>
매개변수
locale: the locale value to be applied on the format() method format: The format of the output string. args: args specifying the number of arguments for the format string. It may be zero or more.>
반환 값
- 형식화된 문자열.
예외 발생
- NullPointer예외: 형식이 null인 경우
- 불법형식예외: 지정된 형식이 잘못되었거나 인수가 부족한 경우입니다.
Java 문자열 형식()의 예
자바
// 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 =>'techcodeview.com'>;> >// 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 techcodeview.com My answer is 47.65734000 My answer is 47.65734000>
Java 형식 지정자
| 형식 지정자 | 데이터 형식 | 출력 또는 반환 값 |
|---|---|---|
| %ㅏ | 부동 소수점 | 부동 소수점 숫자의 16진수 출력을 반환합니다. |
| %비 | 어떤 유형 | 참 또는 거짓 |
| %씨 | 성격 | 유니코드 문자 |
| %디 | 정수 | 십진수 |
| %그것은 | 부동 소수점 | 과학적 표기법의 십진수 |
| %에프 | 부동 소수점 | 십진수 |
| %g | 부동 소수점 | 십진수(정밀도와 값에 따라 과학적 표기법 사용 가능) |
| %시간 js 세트 | 어떤 유형 | hashCode() 메서드의 값을 나타내는 16진수 문자열 |
| %N | 없음 | 플랫폼별 줄 구분 기호 |
| %영형 | 정수 | 8진수 |
| %에스 자바의 소수 | 어떤 유형 | 문자열 값 |
| %티 | 날짜 시간 | %t는 날짜/시간 변환의 접두어입니다. |
| %엑스 | 정수 | 16진수 문자열 |
Java 문자열 형식 지정자의 예
실시예 1
자바
// 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 =>'techcodeview.com'>;> >// %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 techcodeview.com>
실시예 2
자바
// 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);> >}> }> |
C++ 문자열 분할
>
>산출
0007044>