[c++] 문자열 합치기

먼저 + 연산자를 사용하여 문자열을 합쳐보겠습니다.

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "world!";
    std::string result = str1 + str2;
    std::cout << result << std::endl;
    return 0;
}

위 코드는 “Hello, world!”를 출력합니다.

두 번째 방법으로 append 함수를 사용하여 문자열을 합쳐보겠습니다.

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "world!";
    str1.append(str2);
    std::cout << str1 << std::endl;
    return 0;
}

위 코드도 “Hello, world!”를 출력합니다.

이 두 가지 방법 중에 어떤 것을 선택할지는 개인의 취향에 따라 다를 수 있습니다. 보통은 + 연산자가 보다 간결한 코드를 만들 수 있기 때문에 더 자주 사용됩니다.