Write a function Split(...) that is given a string, a separator character, an ar
ID: 3590422 • Letter: W
Question
Write a function Split(...) that is given a string, a separator character, an array to fill and the max number of elements in the array as parameters and returns an integer result. The function will separate each substring of the given string between separator characters and place it in the array. The function returns the number of substrings extracted.
For example:
Split("cow/chicken/fish", '/', words[], size )
would return the count of 3 and fill the array with "cow", "chicken", "fish"
use c++
int Split (string str , char e, string words[ ], int size )
{
words[0]=str;
int h=0;
int f =0;
int c=1;
if(str.length()==0)
{
c=c-1;
}
else {
for(int i=0;i<str.length(); i++)
{
if(str[i]==e)
{
words[h]=str.substr(f,i);
str=str.substr(i+1,str.length());
c++;
h=h+1;
}
}
}
return c;
}
Explanation / Answer
For the above Problem below is the code in c++ :
int Split (string str , char e, string words[ ], int size )
{
int h=0;
int f =0;
int c=1;
size=str.length();
if(size==0)
{
c=c-1;
}
else
{
for(int i=0;i<str.length(); i++)
{
if(str[i]==e)
{
words[h]=str.substr(f,i-f); // this statement will help to fill the array with all words separated by separator.
c++;
h=h+1;
f=i+1;
}
if(i==(size-1))
{
words[h]=str.substr(f,i);
}
}
}
return c;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.