【问题标题】:c++ How to convert string array to char arrayc++ 如何将字符串数组转换为字符数组
【发布时间】:2019-10-12 16:00:57
【问题描述】:

我的程序应该有 store = 5 个字符串值 - Simpsun GN120、Sonic Lux10、Ultimax G42、Antalpha A200 和 Nickov N230,然后进行计算,为每个值生成代码。代码将采用值的前 3 个字母和最后 3 个字母。

值的第一个代码:Simpsun GN120

看起来像这样:Sim120

我最大的问题是我无法创建一个字符串数组,因为获取数组中每个值的长度会导致程序崩溃,所以现在我已经制作了可以执行此计算的程序,但前提是字符串不是数组,如果有人可以给我一些提示,我可以如何改进我的代码以将该字符串放入数组中

#include <iostream>
using namespace std;
int main()
{
    string str = "Simpsun GN120";
    int i;
    string productCode[5];


    for (i = 0; i < str.length(); i++)
    {
        if (i == 0 || i == 1 || i == 2)
        {
            productCode[0] += str[i];
        }
        if (i == str.length() - 1 || i == str.length() - 2 || i == str.length() - 3)
        {
            productCode[0] += str[i];
        }

    }
    cout << productCode[0];

}

【问题讨论】:

  • productCode[0] = str.substr(0, 3) + str.substr(str.length() - 3);
  • 好吧,我可以将字符串转换为 char 数组等等,但问题是我想让那行字符串 str = "Simpsun GN120";在数组中,看起来像这样的字符串 str[5] = {"Simpsun GN120", "Sonic Lux10", "Ultimax G42", "Antalpha A200", "Nickov N230" };稍后我将更改我的字符串数组,它不会分配恒定大小,它会扩展,因为我必须输入每个名称并将其存储在数组中,如“Simpsun GN120”等等。
  • 我当前的代码正在工作,但正如我上面所说的,只有普通字符串,因为如果我想为 str .length 制作字符串数组,我将无法检查数组中每个名称的大小必须为每个名称单独制作代码
  • substr 是什么意思? productCode[0] = str.substr(0, 3) + str.substr(str.length() - 3); @jignatius

标签: c++ arrays string char


【解决方案1】:

使用字符串类很简单。运行一个循环来执行 productCode[i] = str[i].substr(0, 3) + str[i].substr(str[i].length() - 3); 你的工作就完成了。

【讨论】:

    【解决方案2】:

    jignatius 非常感谢您的回答!

    using namespace std;
    int main()
    {
        string str[2] = { "Simpsun GN120", "Sonic Lux10" };
        int i;
        string productCode[5];
    
        for (int i = 0; i < 2; i++)
        {
            productCode[i] = str[i].substr(0, 3) + str[i].substr(str[i].length() - 3);
        }
    
        cout << productCode[0] << endl;
        cout << productCode[1];
    }
    

    【讨论】:

    • 您可以使用 std::vector(可以添加或删除它)或 std::array(固定大小)来代替 C 样式的字符串数组。这更像是 C++ 风格。
    • 我认为数组(固定大小)将不起作用,因为稍后我将使该用户能够输入任意数量的摄影套件并将它们添加到 str 数组中数组会改变我以前从未使用过向量,我仍在尝试学习一些东西,但谢谢你,我会记住它,并会尝试了解更多关于向量的信息
    • 那么 std::vector<:string> 就是你想要的。很高兴我能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2016-11-20
    • 2021-12-13
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多