Reputation: 6391
Write a recursive, string -valued function, replace, that accepts a string and returns a new string consisting of the original string with each blank replaced with an asterisk (*) Replacing the blanks in a string involves:
Nothing if the string is empty
Otherwise: If the first character is not a blank, simply concatenate it with the result of replacing the rest of the string
If the first character IS a blank, concatenate an * with the result of replacing the rest of the string
Here's what I've tried:
string replace(string sentence){
if(sentence.empty()) return sentence;
string newString;
if(sentence[0] == " ") {
newString.append('*' + sentence.substr(1, sentence.length()));
} else {
newString.append(sentence.substr(1, sentence.length()));
}
return replace(newString);
}
But the website that tests the code for the correct answer is giving me the following error:
CTest1.cpp: In function 'std::string replace(std::string)':
CTest1.cpp:9: error: ISO C++ forbids comparison between pointer and integer
Please note that the lines in the error don't necessarily correlate with the actual lines in the code.
Any suggestions?
Update
Solved it using the following code:
string replace(string sentence){
if(sentence.empty()) return sentence;
string newString;
if(sentence[0] == ' ') {
newString.append("*" + replace(sentence.substr(1)));
} else {
newString.append(sentence[0] + replace(sentence.substr(1)));
}
return newString;
}
Upvotes: 0
Views: 5267
Reputation: 1168
Upvotes: 0
Reputation: 11434
string sentence;
if(sentence[0] == " ")
" "
isn´t a single char, but a whole string. If you want a single blank, use ' '
Upvotes: 3