简体   繁体   中英

Writing a recursive string function

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 ' '

  1. In if(sentence[0] == " "), sentence[0] is a character(which may be converted to its ascii value(integer) during comparison) and " " is an empty string or pointer to first character in an empty string. That is what is throwing the error.
  2. Instead do if(sentence[0] == ' '). Also I am not sure in C++, but in java == checks for equality of references. so take care of it as well.
  3. Also you need to append the result of replacing the rest of the string, not just the rest of the string. Write a recursive function for that

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM