답변:
우선 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";
operator+=할당 해제와 할당을 모두 수행 한다는 것 입니다. 힙 할당은 우리가 일반적으로 수행하는 가장 비용이 많이 드는 작업 중 하나입니다.
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 연산자는 인수가 허용되지 않으므로 포인터 만 사용하여 오버로드합니다.
또한이 경우 결과는 동적으로 할당되므로 메모리 누수를 방지하기 위해 delete를 호출하거나 스택 할당 문자 배열을 사용하도록 함수를 수정할 수 있습니다 (물론 길이가 충분한 경우).
strncat()일반적으로 더 나은 대안이다 기능
strncat여기서는 두 번째 매개 변수의 길이를 이미 알고 있기 때문에 관련이 없습니다 ".txt". 그래서 그것은 strncat(name, ".txt", 4)우리에게 아무것도 얻지 못하는.
strcat (destination, source)는 C ++에서 두 문자열을 연결하는 데 사용할 수 있습니다.
깊은 이해를 위해 다음 링크에서 조회 할 수 있습니다.
이전 스타일의 C 문자열 대신 C ++ 문자열 클래스를 사용하는 것이 더 낫습니다. 삶이 훨씬 쉬울 것입니다.
기존의 기존 스타일 문자열이있는 경우 문자열 클래스로 변환 할 수 있습니다.
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
//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;
}