For example if my string is "^^^^^^Big^^^Bob", i want to turn it in to "Big^Bob"

First, you can use the standard function std::unique (from <algorithm> header) to remove any consecutive spaces by using this predicate (requires header <locale> for the std::isspace function):

bool isConsecutiveSpace(char a, char b) {
  if(std::isspace(a) && a == b)
    return true;
  return false;
};

// call std::unique as so:
std::string my_string = "     Big   Bob  ";
std::string::iterator it_end = std::unique(my_string.begin(), 
                                           my_string.end(),
                                           isConsecutiveSpace);

Then, it is just a matter of removing the first and last characters, if any are spaces too. As in:

std::string::iterator it_beg = my_string.begin();
if(std::isspace(*it_beg))
  ++it_beg;

if((it_end != it_beg) && std::isspace(*(it_end - 1)))
  --it_end;

std::string result(it_beg, it_end);  // copy into the result string.

If you'd want a simple if/else if condition program, maybe this would help you:

string rev(char delim, string str){
    string return_string;
    for (size_t i=1;i<str.size();i++){
        if (str[i]==delim && str[i-1]!=delim)
            return_string.push_back(str[i]);
        else if (str[i]!=delim)
            return_string.push_back(str[i]);
    }
    if (str[0]!=delim) return_string.insert(return_string.begin(), str[0]);
    if (*(return_string.end()-1)==delim) return_string.erase(return_string.end()-1);
    return return_string;
}

but mike_2000_17's version is more raffiner, and perhaps better to be followed.

Edited 3 Years Ago by Lucaci Andrew

As far as trimming goes, the following might be useful:

// Trim the start of a string.
string& TrimLeft(string& s)
{
    s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
    return s;
}


// Trim the end of a string.
string& TrimRight(string& s)
{
    s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
    return s;
}


// Trim the ends of a string.
string& Trim(string& s)
{
    return TrimLeft(TrimRight(s));
}

Also, this could be done by using a token (stringstream) and splitting the string by the delimitter:

string rem(string a, char delim){
    string ret, part;
    stringstream token(a);
    while (getline(token, part, delim))
        if (part != "")
            (ret += part).push_back(delim);
    return ret.substr(0, ret.size()-1);
}

Edited 3 Years Ago by Lucaci Andrew

This question has already been answered. Start a new discussion instead.