N0way1998
N0way1998

Reputation: 11

c++ How to convert string array to char array

my program should have store = 5 string values - Simpsun GN120, Sonic Lux10, Ultimax G42, Antalpha A200 and Nickov N230 and then make a calculation that will make code for each value. Code would take first 3 letters and 3 last letters of a value.

first code from value: Simpsun GN120

would look like this: Sim120

my biggest issue was that i couldn't make a string array as getting a length of each value in array would crash a program so for now i have made program that will do this calculation but only if string is not array if someone could give me some tips how i could improve my code to make that string in to array

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

}

Upvotes: 0

Views: 377

Answers (2)

user11716985
user11716985

Reputation:

It's simple using string class .Run a loop to execute productCode[i] = str[i].substr(0, 3) + str[i].substr(str[i].length() - 3); and your work is done.

Upvotes: 1

N0way1998
N0way1998

Reputation: 11

jignatius Thank you very much for that answer!

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

Upvotes: 1

Related Questions