C++ Beginner -- Identifying and reversing letters in a string? I want to write a
ID: 672259 • Letter: C
Question
C++ Beginner -- Identifying and reversing letters in a string?
I want to write a program where I teach a kid their "i before e"s.
I allow them to input a sentence of any length, and I want the program to pick up when they have written "ei" in a word. Say the child would input "I beleive I can fly" the program would output "I believe I can fly."
If the word contains "cei" then I leave it alone-- fulfilling the "except after c" rule. (I know there's a lot of little exceptions like "weird," but I'm not thinking that deep into it yet)
Thanks for the help!
Explanation / Answer
Please find the program as per the requirement:
#include <iostream>
using namespace std;
std::string ReplaceString(std::string subject, const std::string& search, const std::string& replace);
//Identifying and reversing letters in a string
int main() {
string istr,*ptr;
cout<<"Please enter a sentence of any length: "<<endl;
getline( cin, istr ) ;
//cout<<istr<<endl;
istr=ReplaceString(istr,"ei","ie"); //"i before e" Rule
istr=ReplaceString(istr,"cie","cei");//"except after c" Rule
cout<<"Corrected sentence is: "<<endl;
cout<<istr<<endl;
return 0;
}
std::string ReplaceString(std::string subject, const std::string& search,const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.