string strings[10];
void split(string s){
int curr=0,start=0,end=0,i=0;
while(i<=len(s)){
if(s[i]==' ' or i == len(s)){
end = i;
string sub;
sub.append(s,start,end-start);
strings[curr] = sub;
start = end 1;
curr = 1 ;
}
i ;
}
}
for example if the input is " computer laptop screen desktop mouse " then the output string should be: computer laptop screen desktop mouse
I have successfully tried using loops but failed using recursion, can anyone help me solve split() using recursion. Thank you
CodePudding user response:
This solution assumes you want only words from the string to enter your array and that you want to split on some predetermined delimiter like <space>' '
or <dash>'-'
.
If you need to keep the void
function signature, here is one:
void split_rec(string str_array[], size_t arr_index,
string s, char delimiter) {
if (s == "") {
return;
}
size_t delim_index = s.find(delimiter);
string str_to_add = s.substr(0, delim_index);
// This step filters out extra delimiters that would cause empty strings.
if (str_to_add != "") {
str_array[arr_index ] = str_to_add;
}
// find() returns string::npos if it doesnt find delimiter.
if (delim_index == string::npos) {
return;
} else {
split_rec(str_array, arr_index, s.substr(delim_index 1), delimiter);
}
}
But I would recommend returning the size of the array so you communicate what the function is doing more accurately. Like this:
size_t split_rec(string str_array[], size_t arr_index,
string s, char delimiter) {
if (s == "") {
return arr_index;
}
size_t delim_index = s.find(delimiter);
string str_to_add = s.substr(0, delim_index);
if (str_to_add != "") {
str_array[arr_index ] = str_to_add;
}
if (delim_index == string::npos) {
return arr_index;
}
return split_rec(str_array, arr_index, s.substr(delim_index 1), delimiter);
}
Then the call is like this:
string strings[10];
// I left some extra spaces in this string.
string str = " computer laptop screen desktop mouse ";
size_t strings_len = split_rec(strings, 0, str, ' ');
cout << "Array is length " << strings_len << endl;
for (size_t i = 0; i < strings_len; i ) {
cout << strings[i] << endl;
}
Array is length 5
computer
laptop
screen
desktop
mouse