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);
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?
boost
You can use std::uniquewith std::removealong with ::isspaceto compress multiple whitespace into single spaces:
std::unique
std::remove
::isspace
std::remove(std::unique(std::begin(text), std::end(text), [](char c, char c2) { return ::isspace(c) && ::isspace(c2); }), std::end(text));
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
, , , @Nawaz - istringstream, , . , infix_ostream_iterator , (IMO) / .
istringstream
infix_ostream_iterator
std::istringstream buffer(input); std::copy(std::istream_iterator<std::string>(buffer), std::istream_iterator<std::string>(), infix_ostream_iterator<std::string>(result, " "));
#include <boost/algorithm/string/trim_all.hpp> string s; boost::algorithm::trim_all(s);
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(" ")); }
. GCC 4.6 regex_replace, Boost.Regex :
regex_replace
#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; }