如何在 C++ 中将字符串转换为字符数组?


这是一个 C++ 程序,用于在 C++ 中将字符串转换为字符数组。这有许多不同的方式可以做到

类型 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[]="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

我们可以避免使用 strcpy(),其最初通过 std::string::copy 而不是使用 strcpy() 在 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 = "Tutorialspoint";
   char c[str.size() + 1];
   str.copy(c, str.size() + 1);
   c[str.size()] = '\0';
   cout << c << '\n';
   return 0;
}

输出

Tutorialspoint

更新时间:30-Jul-2019

1K+ 浏览

开启你的职业

通过完成课程获得认证

开始
广告
© . All rights reserved.