cpp remove whitespace from string code example
Example 1: c++ remove whitespace from string
#include <algorithm>
int main()
{
std::string str = "H e l l o";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
std::cout << str;
return 0;
}
Example 2: c++ remove trailing whitespace
remove trailing whitespace
Example 3: strip whitespace c++
#include <algorithm>
#include <cctype>
#include <locale>
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
static inline std::string ltrim_copy(std::string s) {
ltrim(s);
return s;
}
static inline std::string rtrim_copy(std::string s) {
rtrim(s);
return s;
}
static inline std::string trim_copy(std::string s) {
trim(s);
return s;
}