I have loaded a text file content to a std::string. And I want to remove the whitespaces from the loaded string.
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*
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With