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;
}
string sentence;
if(sentence[0] == " ")
" "
isn´ta single char, but a whole string. If you want a single blank, use ' '
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.