如何在C ++中将字符串转换为char数组?
这是一个C++程序,用于在C++中将字符串转换为char数组。这可以通过多种不同方式完成
类型1
算法
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;
}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 = "Nhooo";
char c[str.size() + 1];
strcpy(c, str.c_str());
cout << c << '\n';
return 0;
}输出结果
Nhooo
类型3
我们可以避免使用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
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短