compute recursively a
new string where adjacent characters that
are the same have been reduced to a single
character. So "yyzzza" yields "yza".
You must not use loops.
Here are some more examples:

string_clean("yyzzza") returns "yza"
string_clean("abbbcdd") returns "abcd"
string_clean("Hello") returns "Helo"


please give me some suggestion.

Recommended Answers

All 5 Replies

How about a skeleton :

string uniqify(const std::string& source,int currentLocation){
 if(source.length() <= 1) return source;
 else{/*code here */}
}
string string_clean(const std::string& str){
 return uniqify(source,0);
}
string string_clean(const string& str)
{
    if(str.length() == 0) return "";

    if(str[1] == str[0]) return str[0] + string_clean(str.substr(2));
    else return str[0] + string_clean(str.substr(1));
}

my code fail when the char appear 3 times

No you need to check if the current index location has the same value as the previous location and repeat until the end of string

i am kinda confused, can you be more specific please, this is raelly urgent.

suggestion:

//function prototype
string unique_chars(string line, int index = 0);
//function definition
string unique_chars(string line, int index)
{
     int pos = 0;
     string temp;
     
     //recusive exit case
     if(index == line.size())
     {
           return line;
     }

     pos = line.find(line[index], index+1)

     //if no other matching characters in string, move on to the next character
     if(pos == string::npos)
     { 
          return unique_chars(line, index++);
     }
     
     //erase a matching character, then move on to the next character
     else
     {
          line.erase(line.begin()+ pos);
          return unique_chars(line, index++);
     }
}

This is untested code. I just made it up. I don't know if this compiles without error. But you have to admit it's awesome help even if it doesn't work. It's sole intention is to give you an idea.. steer ye' in the right direction. What I would like to see from you now is a show of effort on your part.

Here is a decent youtube on "intro to c++ recursion": http://www.youtube.com/watch?v=kwFMkruKI8Y&feature=related

Here is a list of string class member functions: http://www.cplusplus.com/reference/string/string/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.