C++에서 문자열을 문자 배열로 변환하는 C++ 프로그램입니다. 여러 가지 방법으로 수행할 수 있습니다.
유형 1:
알고리즘
Begin
Assign value to string m.
For i = 0 to sizeof(m)
Print the char array.
End 예제 코드
#include<iostream>
#include<string.h>
using namespace std;
int main() {
char m[] = "Tutorialspoint";
string str;
int i;
for(i=0;i<sizeof(m);i++) {
str[i] = m[i];
cout<<str[i];
}
return 0;
} 유형 2:
strcpy() 함수를 호출하여 문자열을 char 배열에 복사할 수 있습니다.
알고리즘
Begin Assign value to string s. Copying the contents of the string to char array using strcpy(). End
예제 코드
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string str = "Tutorialspoint";
char c[str.size() + 1];
strcpy(c, str.c_str());
cout << c << '\n';
return 0;
} 출력
Tutorialspoint
유형 3:
기본적으로 c에서 사용되는 strcpy() 사용을 피할 수 있습니다.
std::string::copy instead.
알고리즘
Begin Assign value to string s. copying the contents of the string to char array using copy(). End
예제 코드
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Tutorialspoint";
char c[str.size() + 1];
str.copy(c, str.size() + 1);
c[str.size()] = '\0';
cout << c << '\n';
return 0;
} 출력
Tutorialspoint