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;
Explanation:
Please see attachments