Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove white spaces from std::string

Tags:

c++

c++11

c++14

I have loaded a text file content to a std::string. And I want to remove the whitespaces from the loaded string.

  1. Which below method need to be used for better performance?
  2. Which below method can be a best practice.?
  3. Else any better way is there to achieve this?

Method 1:
Scan the string using string.find() in a loop statement and remove whitespace using string.erase();

Method 2:
Scan the string using string.find() in a loop statement and copy the non whitespace characters to a new string() variable using string.append();

Method 3:
Scan the string using string.find() in a loop statement and copy the non whitespace characters to a new string(size_t n, char c) variable using string.replace();

Method 4:
Allocate a char* (using malloc[size of the source string])
Scan the string using string.find() in a loop statement and copy the non whitespace characters to the char* variable using strcpy and then strcat();
finally copy the char* to a new string
free char*

like image 412
Jeet Avatar asked Nov 28 '22 23:11

Jeet


2 Answers

Edit: upgraded to locale-aware trait. Thanks user657267 !

Standards algorithms are neat !

s.erase(std::remove_if(
    begin(s), end(s),
    [l = std::locale{}](auto ch) { return std::isspace(ch, l); }
), end(s));

Live on Coliru

That was for in-place modification, if you need to keep the original string however :

std::string s2;
s2.reserve(s.size());
std::remove_copy_if(
    begin(s), end(s),
    std::back_inserter(s2),
    [l = std::locale{}](auto ch) { return std::isspace(ch, l); }
);

Live on Coliru

like image 105
Quentin Avatar answered Dec 11 '22 00:12

Quentin


IMHO, best performance you can get with method 2, but before appending you need to call std::string::reserve method to set capacity of new string to the size of initial string. This needed to prevent unnecessary reallocations, when appending.

like image 22
Elohim Meth Avatar answered Dec 11 '22 00:12

Elohim Meth