IT박스

문자열 변수 보간 자바

itboxs 2020. 6. 10. 22:53
반응형

문자열 변수 보간 자바


이 질문에는 이미 답변이 있습니다.

Java로 문자열을 작성하면 나를 혼란스럽게합니다. 나는 다음과 같은 일을하고 있습니다.

url += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";
url += "x=" + u1 + ";y=" + u2 + ";z=" + u3 + ";da1=" + u4 + ";";
url += "qty=1;cost=" + orderTotal + ";ord=" + orderId + "?";

또는 StringBuilder를 사용하면 다음과 같습니다.

    url.append("u1=");
    url.append(u1);
    url.append(";u2=");
    url.append(u2);
    url.append(";u3=");
    url.append(u3);
    url.append(";u4=");
    url.append(u4);
    url.append(";");
    url.append("x=");
    url.append(u1);
    url.append(";y=");
    url.append(u2);
    url.append(";z=");
    url.append(u3);
    url.append(";da1=");
    url.append(u4);
    url.append(";");
    url.append("qty=1;");
    url.append("cost=");
    url.append(orderTotal);
    url.append(";ord=");
    url.append(orderId);
    url.append("?");

분명히 뭔가 빠졌습니다. 더 나은 방법이 될 GOT가 있습니다. 다음과 같은 것 :대신에:

urlString += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";

하다:

urlString += Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

또는:

urlStringBuilder.append(Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4));

Java 5 이상을 사용하는 경우 다음을 사용할 수 있습니다

String.format

.

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

자세한 내용

Formatter

을 참조하십시오.


Java에는 변수 보간이 없습니다. 변수 보간은 문자열 내부의 값으로 변수를 대체하는 것입니다. 루비의 예 :

#!/usr/bin/ruby

age = 34
name = "William"

puts "#{name} is #{age} years old" 

Ruby 인터프리터는 변수를 문자열 내의 값으로 자동 대체합니다. 실제로 보간을 수행한다는 것은시길 문자로 암시됩니다. 루비에서는 # {}입니다. Perl에서는 $, % 또는 @ 일 수 있습니다. Java는 그러한 문자 만 인쇄하고 확장하지는 않습니다.Java에서는 변수 보간이 지원되지 않습니다. 이 대신 문자열 형식이 있습니다.

package com.zetcode;

public class StringFormatting 
{
    public static void main(String[] args) 
    {
        int age = 34;
        String name = "William";

        String output = String.format("%s is %d years old.", name, age);

        System.out.println(output);
    }
}

Java에서는 String.format () 메소드를 사용하여 새 문자열을 작성합니다. 결과는 동일하지만 방법이 다릅니다.http://en.wikipedia.org/wiki/Variable_interpolation을 참조하십시오

.

편집

2019 년

JEP 326

(원시 문자열 리터럴)이

JEP 355

(텍스트 블록)에 의해 철회 및 감독되었습니다 . 후자는 언어에 "텍스트 블록"을 도입하려고 시도합니다.

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over format when desired.

However, still no string interpolation:

Non-Goals: Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP.


Just to add that there is also java.text.MessageFormat with the benefit of having numeric argument indexes.

Appending the 1st example from the documentation

int planet = 7;
String event = "a disturbance in the Force";

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
    planet, new Date(), event);

Result:

At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

String.format() to the rescue!!


You can use Kotlin, the Super (cede of) Java for JVM, it has a nice way of interpolating strings like those of ES5, Ruby and Python.

class Client(val firstName: String, val lastName: String) {
    val fullName = "$firstName $lastName"
}

참고URL : https://stackoverflow.com/questions/6389827/string-variable-interpolation-java

반응형