Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming internal whitespace in std::string

I'm looking for an elegant way to transform an 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've already trimmed the external whitespace with boost::trim(text);

[edit] Thus, multiple whitespaces, and tabs, are reduced to just one space [/edit]

Removing the external whitespace is trivial. But is there an elegant way of removing the internal whitespace that doesn't involve manual iteration and comparison of previous and next characters? Perhaps something in boost I have missed?

like image 296
nerozehl Avatar asked Feb 19 '12 16:02

nerozehl


People also ask

How do you trim a space in a string C++?

Given a string, remove all spaces from it. For example “g e e k” should be converted to “geek” and ” g e ” should be converted to “ge”. The idea is to traverse the string from left to right and ignore spaces while traversing.

How do you trim white spaces from a string?

String.prototype.trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


2 Answers

You can use std::unique with std::remove along with ::isspace to compress multiple whitespace characters 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));
like image 111
Seth Carnegie Avatar answered Oct 01 '22 06:10

Seth Carnegie


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
like image 21
Nawaz Avatar answered Oct 01 '22 05:10

Nawaz