자바 사용법Scala의 String.format?
를 사용하려고 합니다..format스트링의 메서드그러나 문자열에 %1, %2 등을 입력하면 java.util이 됩니다.알 수 없는 형식 변환Java 소스 코드 조각을 가리키는 예외가 발생했습니다.
private void checkText(String s) {
int idx;
// If there are any '%' in the given string, we got a bad format
// specifier.
if ((idx = s.indexOf('%')) != -1) {
char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
throw new UnknownFormatConversionException(String.valueOf(c));
}
}
이것으로 알 수 있다%char는 금지되어 있습니다.그렇다면 인수 자리 표시자로 무엇을 사용해야 합니까?
Scala 2.8을 사용합니다.
이전 답변은 모두 맞지만 모두 자바어입니다.Scala의 예를 다음에 나타냅니다.
val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")
Python의 오퍼레이터처럼 만드는 것에 대한 블로그 투고도 있습니다.
위치를 나타내기 위해 숫자를 사용할 필요는 없습니다.기본적으로 인수의 위치는 문자열에 표시되는 순서일 뿐입니다.
다음은 적절한 사용 방법의 예입니다.
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
항상 사용할 수 있습니다.%메서드에 문자열을 표시하는 방법을 알려 주는 기타 문자를 입력합니다. %s아마 가장 일반적일 것입니다.인수가 문자열로 취급되어야 합니다.
모든 옵션을 나열하지는 않지만 몇 가지 예를 들어 아이디어를 제시하겠습니다.
// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals "10 / 3 = 3.33"
// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals "Today we processed 1,000,000 transactions."
String.format를 사용합니다.java.util.Formatter옵션의 상세한 것에 대하여는, Formatter javadocs 를 참조해 주세요.
또한 BalusC가 설명한 바와 같이 필요에 따라 기본 인수 순서를 변경할 수 있는 것을 매뉴얼에서 확인할 수 있습니다.그러나 같은 주장을 여러 번 사용하는 경우만 이 작업을 수행할 필요가 있습니다.
소스 코드를 보는 대신 javadoc String을 읽어야 합니다.format() 및 Formatter 구문.
% 뒤에 값의 형식을 지정합니다.예를 들어 10진수 정수의 경우dString의 경우,s:
String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d", aString, aInt );
출력:
Hello, world on line 20
시도한 작업을 수행하려면(인수 인덱스를 사용합니다) 다음을 사용합니다.*n*$,
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
출력:
Line:20. Value:world. Result: Hello world at line 20
이것을 사용할 수 있습니다.
String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");
출력:
a b b c
또한 Scala는 Predef에서 가져온 WrapedString으로 암묵적으로 변환하여 String을 확장하므로 다음 작업도 수행할 수 있습니다.
val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
공식 참조는 클래스입니다.
Scala 2.10의 경우
val name = "Ivan"
val weather = "sunny"
s"Hello $name, it's $weather today!"
이 리스트는, 이 리스트가 됩니다.String.format할 수 있어요.에 대해서도 마찬가지다.printf
int i = 123;
o.printf( "|%d|%d|%n" , i, -i ); // |123|-123|
o.printf( "|%5d|%5d|%n" , i, -i ); // | 123| –123|
o.printf( "|%-5d|%-5d|%n" , i, -i ); // |123 |-123 |
o.printf( "|%+-5d|%+-5d|%n" , i, -i ); // |+123 |-123 |
o.printf( "|%05d|%05d|%n%n", i, -i ); // |00123|-0123|
o.printf( "|%X|%x|%n", 0xabc, 0xabc ); // |ABC|abc|
o.printf( "|%04x|%#x|%n%n", 0xabc, 0xabc ); // |0abc|0xabc|
double d = 12345.678;
o.printf( "|%f|%f|%n" , d, -d ); // |12345,678000| |-12345,678000|
o.printf( "|%+f|%+f|%n" , d, -d ); // |+12345,678000| |-12345,678000|
o.printf( "|% f|% f|%n" , d, -d ); // | 12345,678000| |-12345,678000|
o.printf( "|%.2f|%.2f|%n" , d, -d ); // |12345,68| |-12345,68|
o.printf( "|%,.2f|%,.2f|%n" , d, -d ); // |12.345,68| |-12.345,68|
o.printf( "|%.2f|%(.2f|%n", d, -d ); // |12345,68| |(12345,68)|
o.printf( "|%10.2f|%10.2f|%n" , d, -d ); // | 12345,68| | –12345,68|
o.printf( "|%010.2f|%010.2f|%n",d, -d ); // |0012345,68| |-012345,68|
String s = "Monsterbacke";
o.printf( "%n|%s|%n", s ); // |Monsterbacke|
o.printf( "|%S|%n", s ); // |MONSTERBACKE|
o.printf( "|%20s|%n", s ); // | Monsterbacke|
o.printf( "|%-20s|%n", s ); // |Monsterbacke |
o.printf( "|%7s|%n", s ); // |Monsterbacke|
o.printf( "|%.7s|%n", s ); // |Monster|
o.printf( "|%20.7s|%n", s ); // | Monster|
Date t = new Date();
o.printf( "%tT%n", t ); // 11:01:39
o.printf( "%tD%n", t ); // 04/18/08
o.printf( "%1$te. %1$tb%n", t ); // 18. Apr
다음은 String과 함께 사용되는 포맷터 목록입니다.포맷()
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
@Londo가 Scala의 "s" 문자열 인터폴레이터를 언급했지만, Scala의 "f" 문자열 인터폴레이터가 원래 질문과 더 관련이 있다고 생각합니다.다른 응답에서도 몇 번 사용한 예는 다음과 같이 기술할 수 있습니다(Scala 2.10 이후).
scala> val name = "Ivan"
name: String = Ivan
scala> val thing = "Scala"
thing: String = Scala
scala> val formatted = f"Hello $name%s, isn't $thing%s cool?"
formatted: String = Hello Ivan, isn't Scala cool?
첫 번째 질문과의 관련성은 다음과 같습니다.
formatted「가 에 붙는 됩니다.에프- 는 "f"를 합니다.
java.util.Formatter java.lang.String.format것을java.util.Formatter
할 수 .이것에 의해, 인수에 일치할 필요는 없습니다.String.format★★★★★★ 。
스칼라에서는 스트링 인터폴레이션에 대해 비용을 절약하고 생활을 훨씬 쉽게 할 수 있는 비용이 있습니다.
예:이름 및 에이징을 입력하고 Hello With the name과 에이징을 말하는 함수를 정의하려고 합니다.다음과 같이 쓸 수 있습니다.
def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is $age"
따라서 이 함수를 호출하면 다음과 같이 됩니다.
funcStringInterpolationDemo("Shivansh",22)
출력은 다음과 같습니다.
Hey ! my name is Shivansh and my age is 22
10년을 더하고 싶은 것처럼 같은 줄에 코드를 작성하여 변경할 수 있습니다!
함수는 다음과 같습니다.
def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is ${age+10}"
이제 출력은 다음과 같습니다.
Hey ! my name is Shivansh and my age is 32
언급URL : https://stackoverflow.com/questions/3695230/how-to-use-java-string-format-in-scala
'source' 카테고리의 다른 글
| 'forward declaration'은 무엇이며 'typeef structure X'와 'structure X'의 차이점은 무엇입니까? (0) | 2022.08.24 |
|---|---|
| 이미 초기화된 Sentry.io 설정에 Vue.js 통합을 추가하려면 어떻게 해야 합니까? (0) | 2022.08.21 |
| Vuex - 변환 유형에 대한 상수이지만 작업 및 Getter에는 해당되지 않습니까? (0) | 2022.08.21 |
| 단일 페이지 vue js 컴포넌트의 UML 클래스 다이어그램을 작성하려면 어떻게 해야 합니까? (0) | 2022.08.21 |
| VueJS / Jest : 여러 가져오기 응답을 조롱합니다. (0) | 2022.08.21 |