如何在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