在 C++ 中将字符串转换为字符数组
这是一个 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() 函数将字符串复制到字符数组中。
算法
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP