Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ problem Write a function in C++ that is similar to the split() function in P

ID: 3579918 • Letter: C

Question

C++ problem

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:

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() )

Explanation / Answer

#include <iostream>

using namespace std;
int Chop(string s){
int count = 1;
string str = "";
for(int i=0; i<s.length(); i++){
if(s[i] == ','){
count++;
cout<<str<<endl;
str = "";
}
else{
str = str + s[i];
}
  
}
cout<<str<<endl;
return count;
}
int main()
{
string s;
  
cout << "Enter the string: ";
cin >> s;
int count = Chop(s);
cout<<"Result = "<<count<<endl;

return 0;
}

Output:

sh-4.2$ g++ -o main *.cpp                                                                                                                                                                                                                              

sh-4.2$ main                                                                                                                                                                                                                                           

Enter the string: cow,chicken,fish                                                                                                                                                                                                                     

cow                                                                                                                                                                                                                                                    

chicken                                                                                                                                                                                                                                                

fish                                                                                                                                                                                                                                                   

Result = 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote