繁体   English   中英

c++ 如何将字符串数组转换为字符数组

[英]c++ How to convert string array to char array

我的程序应该有 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];

}

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];
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM