Trimming inner spaces in std :: string

I am looking for an elegant way to convert std :: string from something like:

std::string text = "   a\t   very  \t   ugly   \t\t\t\t   string       ";

To:

std::string text = "a very ugly string";

I have already trimmed outer spaces with boost::trim(text);

[edit] Thus, multiple spaces and tabs are reduced to one space [/ Edit]

Removing external spaces is trivial. But is there an elegant way to remove internal spaces that doesn't involve manually iterating and comparing previous and next characters? Perhaps something in boostI missed?

+5
source share
6 answers

You can use std::uniquewith std::removealong with ::isspaceto compress multiple whitespace into single spaces:

std::remove(std::unique(std::begin(text), std::end(text), [](char c, char c2) {
    return ::isspace(c) && ::isspace(c2);
}), std::end(text));
+8
source
std::istringstream iss(text);
text = "";
std::string s;
while(iss >> s){
     if ( text != "" ) text += " " + s;
     else text = s;
}
//use text, extra whitespaces are removed from it
+5
source

, , , @Nawaz - istringstream, , . , infix_ostream_iterator , (IMO) / .

std::istringstream buffer(input);

std::copy(std::istream_iterator<std::string>(buffer),
          std::istream_iterator<std::string>(),
          infix_ostream_iterator<std::string>(result, " "));
+3
#include <boost/algorithm/string/trim_all.hpp>
string s;
boost::algorithm::trim_all(s);
+2

https://svn.boost.org/trac/boost/ticket/1808, () :

std::string trim_all ( const std::string &str ) {
return boost::algorithm::find_format_all_copy(
    boost::trim_copy(str),
    boost::algorithm::token_finder (boost::is_space(),boost::algorithm::token_compress_on),
    boost::algorithm::const_formatter(" "));
}
+1

. GCC 4.6 regex_replace, Boost.Regex :

#include <string>
#include <iostream>
// #include <regex>
#include <boost/regex.hpp>
#include <boost/algorithm/string/trim.hpp>

int main() {
  using namespace std;
  using namespace boost;
  string text = "   a\t   very  \t   ugly   \t\t\t\t   string       ";
  trim(text);
  regex pattern{"[[:space:]]+", regex_constants::egrep};
  string result = regex_replace(text, pattern, " ");
  cout << result << endl;
}
0
source

All Articles