nullByteMe
nullByteMe

Reputation: 6391

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;
}

Upvotes: 0

Views: 5267

Answers (2)

prasad vsv
prasad vsv

Reputation: 1168

  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

Upvotes: 0

deviantfan
deviantfan

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

Related Questions