development

Java에서 문자열을 형식화하는 방법

big-blog 2020. 5. 27. 08:19
반응형

Java에서 문자열을 형식화하는 방법


기본적인 질문이지만 다음과 같이 문자열을 어떻게 형식화합니까?

"{2}의 {1} 단계"

Java를 사용하여 변수를 대체하여? C #에서는 쉽습니다.


String.format 외에도 살펴보십시오 java.text.MessageFormat. 형식이 덜 간결하고 제공 한 C # 예제에 조금 더 가깝고 구문 분석에도 사용할 수 있습니다.

예를 들면 다음과 같습니다.

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

더 좋은 예제는 Java 1.5의 varargs 및 autoboxing 개선 사항을 활용하고 위의 내용을 하나의 라이너로 만듭니다.

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat선택 수정 자로 i18nized 복수를 수행하는 데 조금 더 좋습니다. 변수가 1 일 때 단수형을 올바르게 사용하고 그렇지 않으면 복수형 인 메시지를 지정하려면 다음과 같이하면됩니다.

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

String.format을 살펴보십시오 . 그러나 C의 printf 함수 계열과 유사한 형식 지정자를 사용합니다 (예 :

String.format("Hello %s, %d", "world", 42);

"Hello world, 42"를 반환합니다. 형식 지정자에 대해 배울 때 도움 될 수 있습니다 . Andy Thomas-Cramer는 링크를 아래의 주석 에 남겨 두어 공식 사양을 가리키는 것으로 충분히 친절했습니다 . 가장 일반적으로 사용되는 것은 다음과 같습니다.

  • % s-문자열 삽입
  • % d-부호있는 정수 삽입 (10 진수)
  • % f-실수, 표준 표기법 삽입

선택적 형식 지정자와 함께 위치 참조를 사용하는 C #과는 근본적으로 다릅니다. 즉, 다음과 같은 작업을 수행 할 수 없습니다.

String.format("The {0} is repeated again: {0}", "word");

... 실제로 printf / format에 전달 된 매개 변수를 반복하지 않습니다. (아래 스크럼 마이스터의 의견 참조)


결과를 직접 인쇄하려는 경우 원하는대로 System.out.printf ( PrintStream.printf )를 찾을 수 있습니다 .


나는 그것에 대한 간단한 방법을 썼다.

public class SomeCommons {
    /** Message Format like 'Some String {0} / {1}' with arguments */
    public static String msgFormat(String s, Object... args) {
        return new MessageFormat(s).format(args);
    }
}

그래서 당신은 그것을 다음과 같이 사용할 수 있습니다 :

SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");

public class StringFormat {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
                System.out.println(String.format("%-15s%03d",s1,x));
            }
            System.out.println("================================");

    }
}

아웃 팟 "===============================
ved15space123 ved15space123 ved15space123"============ =====================

자바 솔루션

  • "-"는 들여 쓰기를하는 데 사용됩니다

  • "15"는 문자열의 최소 길이를 15로 만듭니다.

  • "s"(% 뒤에 몇 문자)는 문자열로 대체됩니다
  • 0은 정수를 왼쪽에 0으로 채 웁니다.
  • 3은 정수를 최소 길이 3으로 만듭니다.

If you choose not to use String.format, the other option is the + binary operator

String str = "Step " + a + " of " + b;

This is the equivalent of

new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));

Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the + operator (which does a StringBuilder.append(String.valueOf(X))) and find it easier to read.


This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this

/customer/{0}/user/{1}/order

and add as many params as you need:

public String createURL (String restURL, Object ... params) {       
    return new MessageFormat(restURL).format(params);
}

You just have to call this method like this:

createURL("/customer/{0}/user/{1}/order", 123, 321);

The output

"/customer/123/user/321/order"

참고URL : https://stackoverflow.com/questions/6431933/how-to-format-strings-in-java

반응형