在 C++ 中将字符串转换为字符数组
c++server side programmingprogramming
这是一个在 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:
我们可以避免使用 strcpy(),它基本上在 c 中使用,方法是
std::string::copy。
算法
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