【发布时间】: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