更新时间:2023-11-15 17:10:16
如果要用单个空格替换任意数量的空格,则可以使用标准的unique(_copy)
算法来做到这一点:
If the idea is to replace any number of spaces with a single space, then the standard unique(_copy)
algorithm can be tricked to do that:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <boost/lambda/lambda.hpp>
std::string remove_excessive_spaces(const std::string& s)
{
using namespace boost::lambda;
std::string result;
//consider consequtive chars equal only if they are both spaces.
unique_copy(s.begin(), s.end(), back_inserter(result), _1 == ' ' && _2 == ' ');
return result;
}
int main(void)
{
std::string s4="Hai ad asdasd asdasd";
std::cout << remove_excessive_spaces(s4);
}