I am trying to write a program that reads in a line of text and replaces all four letter words with the word "Love".
Example:
I hate you! TO I love you!
This is what I got so far.
# include %26lt;iostream%26gt;
# include %26lt;string%26gt;
using namespace std;
int main(){
string sentence;
cout%26lt;%26lt;"Please enter a sentence."%26lt;%26lt;endl;
getline(cin,sentence);
int spaceOne=0, spaceTwo=0;
while(spaceOne%26lt;sentence.size())
{
spaceOne = sentence.find(' ', spaceOne);
spaceTwo = sentence.find(' ', spaceOne);
if((spaceTwo-spaceOne)==4)
{
sentence.replace(spaceOne+1, 4, "love");
spaceOne = spaceTwo;
} else
{
spaceOne=spaceTwo;
}
}
cout%26lt;%26lt;sentence;
return 0;
}
C++ Programming Help Replacing Four Letter Words With "Love"?
sounds like you need to use a regular expression
Reply:Try using the string::replace method.
http://www.cplusplus.com/reference/strin...
Reply:using
/**
* fill oc with raw repalce the find with replacement
*/
int replace_all(char oc[], char raw[], char find[], char replacement[])
{
.....
complete source can be found http://iqueen.wikidot.com/src:str-util-c
e.g.
// s1, s2 are char arrays
s1 = "I really hate you";
replace_all(s2, s1, "hate", "love");
Reply:You need to find a way to make sure that spaceOne is not always equal to spaceTwo like it is in your implementation.
I believe this is all you need, but I didn't test it:
spaceTwo = sentence.find(' ', spaceOne+1);
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment