programing

문자 배열을 문자열로 변환하는 방법은 무엇입니까?

elecom 2023. 4. 28. 20:10
반응형

문자 배열을 문자열로 변환하는 방법은 무엇입니까?

C++ 변환stringchar 배열로 가는 것은 매우 직선적입니다.c_str끈의 기능과 그 다음에 하는 것.strcpy하지만, 어떻게 그 반대를 할 수 있을까요?

다음과 같은 문자 배열이 있습니다.char arr[ ] = "This is a test";다음으로 다시 변환:string str = "This is a test.

string클래스에는 NULL 종단 C 문자열을 사용하는 생성자가 있습니다.

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

다른 해결책은 이렇게 보일 수도 있습니다.

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

추가 변수를 사용하지 않도록 합니다.

상위 투표 답변에 작은 문제가 있습니다.즉, 문자 배열은 0을 포함할 수 있습니다.위에서 지적한 것처럼 단일 매개 변수가 있는 생성자를 사용할 경우 일부 데이터가 손실됩니다.가능한 해결책은 다음과 같습니다.

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

출력:

123
123 123

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

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

출력:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long

OP에 기반한 약간의 <O/T>, 그러나 나는 "c++ 컨버터"를 구글링했습니다.std::arraychar to string" 그리고 그것은 나를 여기로 데려왔지만, 기존의 답변 중 어떤 것도 다루지 않습니다.std::array<char, ..>:

#include <string>
#include <iostream>
#include <array>
 
int main()
{
  // initialize a char array with "hello\0";
  std::array<char, 6> bar{"hello"};
  // create a string from it using the .data() ptr,
  // this uses the `const char*` ctor of the string
  std::string myString(bar.data());
  // output
  std::cout << myString << std::endl;

  return 0;
}

산출량

hello

시연

언급URL : https://stackoverflow.com/questions/8960087/how-to-convert-a-char-array-to-a-string

반응형