programing

const char*연결

prostudy 2022. 9. 19. 23:25
반응형

const char*연결

다음과 같은 두 개의 연속 문자를 연결해야 합니다.

const char *one = "Hello ";
const char *two = "World";

어떻게 하면 좋을까요?

나는 이것들을 통과했다.char*C 인터페이스를 갖춘 서드파티 라이브러리의 s는, 간단하게 사용할 수 없습니다.std::string대신.

예에서 1과 2는 char 상수를 가리키는 char 포인터입니다.이러한 포인터가 가리키는 문자 상수는 변경할 수 없습니다.예를 들어 다음과 같습니다.

strcat(one,two); // append string two to string one.

동작하지 않습니다.대신 결과를 유지하기 위해 별도의 변수(char 배열)를 사용해야 합니다.다음과 같은 경우:

char result[100];   // array to hold the result.

strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.

C의 방법:

char buf[100];
strcpy(buf, one);
strcat(buf, two);

C++ 방식:

std::string buf(one);
buf.append(two);

컴파일 시간 방법:

#define one "hello "
#define two "world"
#define concat(first, second) first second

const char* buf = concat(one, two);

사용.std::string:

#include <string>

std::string result = std::string(one) + std::string(two);
const char *one = "Hello ";
const char *two = "World";

string total( string(one) + two );

// to use the concatenation as const char*, use:
total.c_str()

업데이트됨: 변경됨string total = string(one) + string(two);로.string total( string(one) + two );퍼포먼스상의 이유(스트링 2 및 임시 스트링 합계)

// string total(move(move(string(one)) + two));  // even faster?

C++ 를 사용하고 있다면,std::stringC스타일의 스트링 대신?

std::string one="Hello";
std::string two="World";

std::string three= one+two;

이 문자열을 C 함수에 전달해야 할 경우, 단순히 전달만 하면 됩니다.three.c_str()

문자열 크기를 모르는 경우 다음과 같은 작업을 수행할 수 있습니다.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    const char* q1 = "First String";
    const char* q2 = " Second String";

    char * qq = (char*) malloc((strlen(q1)+ strlen(q2))*sizeof(char));
    strcpy(qq,q1);
    strcat(qq,q2);

    printf("%s\n",qq);

    return 0;
}

또 하나의 예:

// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(one) + strlen(two) + 1;

// allocate enough memory for the concatenated string:
char* concatString = new char[ bufferSize ];

// copy strings one and two over to the new buffer:
strcpy( concatString, one );
strcat( concatString, two );

...

// delete buffer:
delete[] concatString;

그러나 특별히 C++ 표준 라이브러리를 사용하지 않거나 사용할 수 없는 경우를 제외하고std::string아마 더 안전할 거예요

C 라이브러리와 함께 C++를 사용하고 있는 것 같기 때문에 C++를 사용할 필요가 있습니다.const char *.

그것들을 포장할 것을 제안합니다.const char *안으로std::string:

const char *a = "hello "; 
const char *b = "world"; 
std::string c = a; 
std::string d = b; 
cout << c + d;

우선 동적 메모리 공간을 만들어야 합니다.그러면 두 줄을 그 안에 묶으면 돼요.또는 c++ "string" 클래스를 사용할 수 있습니다.구식 C 방식:

  char* catString = malloc(strlen(one)+strlen(two)+1);
  strcpy(catString, one);
  strcat(catString, two);
  // use the string then delete it when you're done.
  free(catString);

새로운 C++ 방식

  std::string three(one);
  three += two;

사용할 수 있습니다.strstream공식적으로는 권장되지 않지만, C 스트링으로 작업할 필요가 있는 경우에도 매우 유용한 도구라고 생각합니다.

char result[100]; // max size 100
std::ostrstream s(result, sizeof result - 1);

s << one << two << std::ends;
result[99] = '\0';

이것은 쓸 것이다.one그리고 나서.two스트림에 접속하여 끝부분을 부가합니다.\0사용.std::ends두 문자열이 모두 정확하게 작성될 수 있는 경우99문자 - 공백이 남아 있지 않습니다.\0- 마지막 위치에 수동으로 씁니다.

const char* one = "one";
const char* two = "two";
char result[40];
sprintf(result, "%s%s", one, two);

메모리의 동적 할당에서 strcpy 명령을 사용하지 않고 2개의 고정 char 포인터를 연결합니다.

const char* one = "Hello ";
const char* two = "World!";

char* three = new char[strlen(one) + strlen(two) + 1] {'\0'};

strcat_s(three, strlen(one) + 1, one);
strcat_s(three, strlen(one) + strlen(two) + 1, two);

cout << three << endl;

delete[] three;
three = nullptr;

언급URL : https://stackoverflow.com/questions/1995053/const-char-concatenation

반응형