在 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

更新于:2019 年 7 月 30 日

3K+ 次查看

开始您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.