这是一个C ++程序,用于在C ++中将字符串转换为char数组。这可以通过多种不同方式完成
Begin Assign a string value to a char array variable m. Define and string variable str For i = 0 to sizeof(m) Copy character by character from m to str. Print character by character from str. End
#include<iostream> #include<string.h> using namespace std; int main(){ char m[]="Nhooo"; string str; int i; for(i=0;i<sizeof(m);i++) { str[i]=m[i]; cout<<str[i]; } return 0; }
我们可以简单地调用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 = "Nhooo"; char c[str.size() + 1]; strcpy(c, str.c_str()); cout << c << '\n'; return 0; }
输出结果
Nhooo
我们可以避免使用strcpy()
std::string::copy基本上在c中使用的方法。
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 = "Nhooo"; char c[str.size() + 1]; str.copy(c, str.size() + 1); c[str.size()] = '\0'; cout << c << '\n'; return 0; }
输出结果
Nhooo