One of the most common is dealing with whitespace (space, tab, vertical tab, feed, carriage return, newline). Or in c++ speak:
Code: Select all
const std::string whitespace = " \t\v\f\r\n" ;
Code: Select all
//=====================================================================
std::string rtrim(const std::string &value) {
auto loc = value.find_last_not_of(whitespace) + 1;
return value.substr(0,loc);
}
So for instance, if the string was "hello ", the find_last not of() would result in 4 , the location of the last non whitespace character. One is added to it, to create the length of the string we want to extract (remember, locations are zero indexed).
we can do something similar for trimming the front of a string (left of the string):
Code: Select all
//=====================================================================
std::string ltrim(const std::string &value) {
auto loc = value.find_first_not_of(whitespace) ;
if (loc == std::string::npos){
return std::string();
}
return value.substr(loc);
So to trim a string on both sides, just becomes something as easy as :
Code: Select all
//=====================================================================
std::string trim(const std::string &value){
return ltrim(rtrim(value));
}
Code: Select all
//=====================================================================
std::string simplify(const std::string &value) {
auto temp = trim(value) ;
auto append = false ;
std::string rvalue ;
for (auto &ch : temp){
if (!std::isspace(static_cast<int>(ch))){
append = true ;
rvalue += ch;
}
else {
if (append) {
rvalue += ' ';
append = false ;
}
}
}
return rvalue ;
}
Now a simpler version, but perhaps slower, is to use regex functions
Code: Select all
std::string simplify(const std::string& input){
std::regex re("\\s{2,}");
std::string fmt = " ";
auto output = regex_replace(input, re, fmt);
return output ;
}