Nice programing

Java에서 두 문자열을 어떻게 연결합니까?

nicepro 2020. 11. 22. 20:35
반응형

Java에서 두 문자열을 어떻게 연결합니까?


Java에서 문자열을 연결하려고합니다. 왜 작동하지 않습니까?

public class StackOverflowTest {  
    public static void main(String args[]) {
        int theNumber = 42;
        System.out.println("Your number is " . theNumber . "!");
    }
}

+연산자를 사용하여 문자열을 연결할 수 있습니다 .

System.out.println("Your number is " + theNumber + "!");

theNumber암시 적으로 String로 변환됩니다 "42".


자바의 연결 연산자이다 +하지.

시작하기 전에이 내용 (모든 하위 섹션 포함)을 읽으십시오 . PHP 방식으로 생각하는 것을 중지하려고;)

Java에서 문자열 사용에 대한 관점을 넓히기 +위해 문자열 연산자는 실제로 컴파일러에 의해 다음과 유사한 것으로 변환됩니다.

new StringBuilder().append("firstString").append("secondString").toString()

이 질문에 대한 두 가지 기본 답변이 있습니다.

  1. [단순] +연산자를 사용합니다 (문자열 연결). "your number is" + theNumber + "!"(다른 곳에서 언급 한대로)
  2. [간단하지 않음] : StringBuilder(또는 StringBuffer)을 사용합니다.
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");

value.toString();

다음과 같은 스태킹 작업을 권장하지 않습니다.

new StringBuilder().append("I").append("like to write").append("confusing code");

편집 : Java 5부터 문자열 연결 연산자가 StringBuilder컴파일러에 의해 호출로 변환됩니다 . 이 때문에 위의 두 방법이 동일합니다.

참고 :이 문장에서 알 수 있듯이 우주 가치가있는 상품입니다.

주의 사항 : 아래 예 1은 여러 StringBuilder인스턴스를 생성 하며 아래 예 2보다 효율성이 떨어집니다.

예 1

String Blam = one + two;
Blam += three + four;
Blam += five + six;

예 2

String Blam = one + two + three + four + five + six;

기본적으로 달성하려고 할 때 변수 값을 a에 주입하는 세 가지 방법String있습니다.

1. 가장 간단한 방법

+a String와 객체 또는 기본 유형 사이에 연산자를 사용하면 됩니다. 그러면 자동으로 String

  1. 물체의 경우에, 값 String.valueOf(obj)(가)에 대응하는 String" null"경우가 obj있다 null그렇지 값 obj.toString().
  2. 기본 유형의 경우 String.valueOf(<primitive-type>).

null객체 가 아닌 예 :

Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

산출:

Your number is 42!

null개체 가있는 예 :

Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");

산출:

Your number is null!

기본 유형의 예 :

int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");

산출:

Your number is 42!

2. 명시적인 방법과 잠재적으로 가장 효율적인 방법

메서드를 사용하여 빌드하기 위해 StringBuilder(또는 StringBuffer스레드로부터 안전한 오래된 대응 물)을 사용할 수 있습니다 .Stringappend

예:

int theNumber = 42;
StringBuilder buffer = new StringBuilder()
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)

산출:

Your number is 42!

이면에서 이것은 실제로 최근 자바 컴파일러 String가 operator를 사용하여 수행 된 모든 연결을 변환하는 +방법이며, 이전 방법과의 유일한 차이점은 모든 권한 이 있다는 것 입니다.

실제로 컴파일러는 기본 생성자를 사용 하므로 기본 용량 ( 16)은 String빌드 할 최종 길이가 무엇인지 알지 못 하기 때문에 최종 길이 16가. 성능 측면에서 가격.

따라서 최종 크기 String가보다 클 것이라는 것을 미리 알고 있다면 16이 방법을 사용하여 더 나은 초기 용량을 제공하는 것이 훨씬 더 효율적입니다. 예를 들어, 우리의 예에서는 String길이가 16보다 큰을 생성 하므로 더 나은 성능을 위해 다음과 같이 다시 작성해야합니다.

최적화 된 예 :

int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
    .append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)

산출:

Your number is 42!

3. 가장 읽기 쉬운 방법

메서드를 사용 String.format(locale, format, args)하거나 String.format(format, args)둘 다를 사용 Formatter하여 String. 이를 통해 String인수 값으로 대체 될 자리 표시자를 사용하여 최종 형식을 지정할 수 있습니다 .

예:

int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);

산출:

Your number is 42!
Your number is still 42 with printf!

이 접근 방식의 가장 흥미로운 점은 String읽기가 훨씬 쉽고 유지 관리가 훨씬 쉽기 때문에 최종 결과물에 대한 명확한 아이디어를 가지고 있다는 사실입니다 .


자바 8 방식 :

StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);


StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);

PHP 프로그래머 여야합니다.

+표지판을 사용 하십시오.

System.out.println("Your number is " + theNumber + "!");

"."대신 "+"


+문자열 연결에 사용 합니다.

"Your number is " + theNumber + "!"

이것은 작동합니다

public class StackOverflowTest
{  
    public static void main(String args[])
    {
        int theNumber = 42;
        System.out.println("Your number is " + theNumber + "!");
    }
}

두 문자열의 정확한 연결 작업을 위해 다음을 사용하십시오.

file_names = file_names.concat(file_names1);

귀하의 경우 +대신.


더 나은 성능을 위해 str1.concat(str2)where str1str2are 문자열 변수를 사용하십시오.


Java에서 연결 기호는 " +"입니다. jdbc를 사용하는 동안 두 개 또는 세 개의 문자열을 연결하려는 경우 다음을 사용하십시오.

String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);

여기서 ""는 공간에만 사용됩니다.


Java에서 연결 기호는 "."가 아니라 "+"입니다.


"+"가 아니라 "."

그러나 문자열 연결에주의하십시오. 다음은 IBM DeveloperWorks의 몇 가지 생각을 소개하는 링크 입니다.


첫 번째 방법 : 문자열을 연결하는 데 "+"기호를 사용할 수 있지만 이는 항상 인쇄에서 발생합니다. 또 다른 방법 : String 클래스에는 두 문자열을 연결하는 메서드가 포함되어 있습니다. string1.concat (string2);


import com.google.common.base.Joiner;

String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));

이것은 op의 질문에 답하기에는 과잉 일 수 있지만 더 복잡한 조인 작업에 대해 알아두면 좋습니다. 이 stackoverflow 질문은이 분야의 일반적인 Google 검색에서 높은 순위를 차지하므로 알아두면 좋습니다.


stringbuffer, stringbuilder를 사용할 수 있으며 이전에 언급 한 모든 사람이 "+"를 사용할 수 있습니다. "+"가 얼마나 빠른지 잘 모르겠지만 (짧은 문자열의 경우 가장 빠르다고 생각합니다), 오래 동안 빌더와 버퍼가 거의 같다고 생각합니다 (빌더는 동기화되지 않기 때문에 약간 더 빠릅니다).


+연산자를 사용하여 문자열을 연결할 수 있습니다 .

String a="hello ";
String b="world.";
System.out.println(a+b);

산출:

hello world.

그게 다야


다음은 세 번째 변수를 사용하지 않고 2 개의 문자열을 읽고 연결하는 예입니다.

public class Demo {
    public static void main(String args[]) throws Exception  {
        InputStreamReader r=new InputStreamReader(System.in);     
        BufferedReader br = new BufferedReader(r);
        System.out.println("enter your first string");
        String str1 = br.readLine();
        System.out.println("enter your second string");
        String str2 = br.readLine();
        System.out.println("concatenated string is:" + str1 + str2);
    }
}

There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.

Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.

String first = "I eat";  String second = "all the rats."; 
System.out.println(first+second);

So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.

Different ways by which Strings could be concatenated in Java

  1. By using + operator (20 + "")
  2. By using concat method in String class
  3. Using StringBuffer
  4. By using StringBuilder

Method 1:

This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.

String temp = "" + 200 + 'B';

//This is translated internally into,

new StringBuilder().append( "" ).append( 200 ).append('B').toString();

Method 2:

This is the inner concat method's implementation

public String concat(String str) {
    int olen = str.length();
    if (olen == 0) {
        return this;
    }
    if (coder() == str.coder()) {
        byte[] val = this.value;
        byte[] oval = str.value;
        int len = val.length + oval.length;
        byte[] buf = Arrays.copyOf(val, len);
        System.arraycopy(oval, 0, buf, val.length, oval.length);
        return new String(buf, coder);
    }
    int len = length();
    byte[] buf = StringUTF16.newBytesFor(len + olen);
    getBytes(buf, 0, UTF16);
    str.getBytes(buf, len, UTF16);
    return new String(buf, UTF16);
}

This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.

Method 3:

This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.

    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = value.length >> coder;
        int newCapacity = (oldCapacity << 1) + 2;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
        return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }

    private int hugeCapacity(int minCapacity) {
        int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
        int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
        if (UNSAFE_BOUND - minCapacity < 0) { // overflow
            throw new OutOfMemoryError();
        }
        return (minCapacity > SAFE_BOUND)
            ? minCapacity : SAFE_BOUND;
    }

Method 4

StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.

In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.

참고URL : https://stackoverflow.com/questions/3753869/how-do-i-concatenate-two-strings-in-java

반응형