developer tip

C ++에서 두 문자열을 연결하는 방법은 무엇입니까?

copycodes 2020. 9. 9. 08:09
반응형

C ++에서 두 문자열을 연결하는 방법은 무엇입니까?


디렉토리에있는 파일을 열 수 있도록 확장자 char name[10]를 추가하고 싶은 개인 클래스 변수 .txt있습니다.

어떻게해야합니까?

연결된 문자열을 보유하는 새 문자열 변수를 만드는 것이 좋습니다.


우선 char*또는을 사용하지 마십시오 char[N]. 를 사용 std::string하면 다른 모든 것이 너무 쉬워집니다!

예,

std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!

쉽죠?

이제 char const *어떤 함수에 전달하려는 경우와 같이 어떤 이유로 필요한 경우 다음을 수행 할 수 있습니다.

some_c_api(s.c_str(), s.size()); 

이 함수가 다음과 같이 선언되었다고 가정합니다.

some_c_api(char const *input, size_t length);

std::string여기에서 시작하여 자신을 탐색 하십시오.

도움이 되었기를 바랍니다.


C ++이므로 std::string대신 사용하지 않는 이유 char*무엇입니까? 연결은 간단합니다.

std::string str = "abc";
str += "another";

C로 프로그래밍하는 경우 name실제로 말한 것처럼 고정 길이 배열 이라고 가정 하면 다음과 같은 작업을 수행해야합니다.

char filename[sizeof(name) + 4];
strcpy (filename, name) ;
strcat (filename, ".txt") ;
FILE* fp = fopen (filename,...

이제 왜 모두가 추천하는지 알 std::string겠습니까?


"C 스타일 문자열"연결을 수행하는 이식 된 C 라이브러리 strcat () 함수가 있습니다.

BTW C ++에는 C 스타일 문자열을 처리 할 수있는 많은 함수가 있지만 다음과 같이이를 수행하는 자신의 함수를 생각해 보는 것이 도움이 될 수 있습니다.

char * con(const char * first, const char * second) {
    int l1 = 0, l2 = 0;
    const char * f = first, * l = second;

    // step 1 - find lengths (you can also use strlen)
    while (*f++) ++l1;
    while (*l++) ++l2;

    char *result = new char[l1 + l2];

    // then concatenate
    for (int i = 0; i < l1; i++) result[i] = first[i];
    for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];

    // finally, "cap" result with terminating null char
    result[l1+l2] = '\0';
    return result;
}

...그리고...

char s1[] = "file_name";
char *c = con(s1, ".txt");

... 그 결과는 file_name.txt.

직접 작성하려는 유혹을받을 수도 operator +있지만 IIRC 연산자는 인수가 허용되지 않으므로 포인터 만 사용하여 오버로드됩니다.

Also, don't forget the result in this case is dynamically allocated, so you might want to call delete on it to avoid memory leaks, or you could modify the function to use stack allocated character array, provided of course it has sufficient length.


It is better to use C++ string class instead of old style C string, life would be much easier.

if you have existing old style string, you can covert to string class

    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout<<greeting + "and there \n"; //will not compile because concat does \n not work on old C style string
    string trueString = string (greeting);
    cout << trueString + "and there \n"; // compiles fine
    cout << trueString + 'c'; // this will be fine too. if one of the operand if C++ string, this will work too

strcat(destination,source) can be used to concatenate two strings in c++.

To have a deep understanding you can lookup in the following link-

http://www.cplusplus.com/reference/cstring/strcat/


//String appending
#include <iostream>
using namespace std;

void stringconcat(char *str1, char *str2){
    while (*str1 != '\0'){
        str1++;
    }

    while(*str2 != '\0'){
        *str1 = *str2;
        str1++;
        str2++;
    }
}

int main() {
    char str1[100];
    cin.getline(str1, 100);  
    char str2[100];
    cin.getline(str2, 100);

    stringconcat(str1, str2);

    cout<<str1;
    getchar();
    return 0;
}

참고URL : https://stackoverflow.com/questions/15319859/how-to-concatenate-two-strings-in-c

반응형