[英]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.