Write a function in C++ that is similar to the split() function in Python. Chop(
ID: 3580026 • Letter: W
Question
Write a function in C++ that is similar to the split() function in Python. Chop(...) is given a string and a separator character as parameters and returns an integer result. The function will print each substring of the given string between separator characters. The function returns the number of substrings printed. For example: Chop("cow,chicken,fish", ',') would return 3 and the output displayed on the console would be: cow chicken fish Hint: Remember that you can cast the unsigned integer returned by the string function length() to an integer. (e.g. int_value < (int)str.length() ) I have int Chop(string a, char N) { string a = 0; char b = 0; int count = 0; for(i = 0 ; i < (int)str.length() ; i++) { if str[i] == N; { cout << i << endl; count ++; } return count; } } but not working
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int chop(string a,char ch)
{
int l = a.length();
int prev,curr,tmp,ans=0;
prev=0;
for(int i=0,tmp=0;i<l;i++)
{
if(a.at(i)==ch)
{
cout<<a.substr(prev,tmp)<<endl;
prev +=tmp+1;
tmp=0;
ans++;
}
else
{
tmp++;
}
}
cout<<a.substr(prev,tmp)<<endl;
return ans+1;
}
int main()
{
cout<<chop("We have arrived!",' ')<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.