【问题标题】:is There some function that make a conversion from string to array in C++是否有一些函数可以在 C++ 中进行从字符串到数组的转换
【发布时间】:2022-01-25 13:37:50
【问题描述】:
string x = "Banana";

如何将其转换为这样的字符:

char x[]={'B', 'a', 'n', 'a', 'n', 'a'};

【问题讨论】:

  • 请记住,在标准 c++ 中,数组在编译时必须具有固定大小。
  • 是的,我知道这只是一个例子
  • std::string 已经管理了一个 char 数组。你需要它做什么?你想要达到的最终目标是什么?这看起来像 XY problem
  • .data().c_str() 应该足够了。你需要它做什么?

标签: c++ arrays string char


【解决方案1】:

你可以在c++中按照这种方式将字符串转换为字符数组。

#include <iostream>
#include <cstring>
 
using namespace std;

int main()
{
    // assigning value to string s
    string s = "Banana";
 
    int n = s.length();
 
    // declaring character array
    char char_array[n + 1];
 
    // copying the contents of the
    // string to char array
    strcpy(char_array, s.c_str());
 
    // this part need to be deleted. This is only for verification.
    for (int i = 0; i < n; i++)
        cout << char_array[i] << endl;
 
    return 0;
}

【讨论】:

  • char char_array[n + 1]; 不是标准 C++... 数组需要恒定大小。
  • 而且没有理由有一个单独的数组。你可以用数组做的所有事情,你都可以用字符串本身来做。
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 2021-08-08
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
相关资源
最近更新 更多