18.2k views
4 votes
Now, extend your test program by adding a second function named split that will identify all the individual values in a comma separated value string and return them in an array of string objects: int split(string str, string a[], int max_size); Your function will take three arguments: a comma separated value string str, an array a of string objects, and the maximum size of the array. You must use the nextString function from Stretch Problem (1) to obtain each value in the string and store it in the array starting, with the first element. Return the total number of values stored in the array. For example: string varray[VALUES]; 2 int cnt

User Iravanchi
by
4.4k points

1 Answer

0 votes

Answer:

The code to copy is :

#include <iostream>

#include <string>

using namespace std;

string nextString(string str, int start_index);

int split(string str, string a[], int max_size);

int main()

{

const int VALUES = 20;

string somestring;

string varray[VALUES];

//Prompt the user to enter a comma separated string

cout << "Enter a comma seperated string: ";

//read the string

getline(cin, somestring);

//call split() method on the given string and

//store the count of individual strings in cnt

int cnt = split(somestring, varray, VALUES);

//Print the individual strings

for (int i = 0; i<cnt; i++)

cout << varray[i] << endl;

return 0;

}

//returns a sub string that starts at strat_index

//in the given string and ends before a comma

string nextString(string str, int start_index)

{

int i;

//find a comma or end of the string, after strat_index

for (i = start_index;i < str.length();i++)

{

//if comma is found, exit the loop

if (str.at(i) == ',')

break;

}

//extract the sub string

string out= str.substr(start_index, i-start_index);

return out;

}

//splits the comma separted string as individual strings

//and returns the number of individual strings

int split(string str, string a[], int max_size)

{

int i, j;

int start_index = 0;

//search for commas in the given string

for (i = 0,j=0;i < str.length();i++)

{

//if comma is identified or end of the string is identified

//, then get a strig that starts at start_index using next string

if (str.at(i) == ',' ||i==str.length()-1)

{

//save each string into an array of strings

a[j] = nextString(str, start_index);

//update the next string starting postion(starts after comma)

start_index = i + 1;

j++;

}

}

return j;

Step-by-step explanation:

Please see attachments

Now, extend your test program by adding a second function named split that will identify-example-1
Now, extend your test program by adding a second function named split that will identify-example-2
User Gilm
by
4.7k points