Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Last active May 31, 2021 18:08
Show Gist options
  • Save dedeexe/9080526 to your computer and use it in GitHub Desktop.
Save dedeexe/9080526 to your computer and use it in GitHub Desktop.
Trimming string in C++
#include <string>
#include <iostream>
//
//Left trim
//
std::string trim_left(const std::string& str)
{
const std::string pattern = " \f\n\r\t\v";
return str.substr(str.find_first_not_of(pattern));
}
//
//Right trim
//
std::string trim_right(const std::string& str)
{
const std::string pattern = " \f\n\r\t\v";
return str.substr(0,str.find_last_not_of(pattern) + 1);
}
//
//Left and Right trim
//
std::string trim(const std::string& str)
{
return trim_left(trim_right(str));
}
//
// How to use:
//
int main(int argc, char **argv)
{
std::string source = " Parangari kutiri miruaro ";
std::string str_trim_left = trim_left(source);
std::string str_trim_right = trim_right(source);
std::string str_trim_all = trim(source);
std::cout << "\"" << source << "\"" << std::endl;
std::cout << "\"" << str_trim_left << "\"" << std::endl;
std::cout << "\"" << str_trim_right << "\"" << std::endl;
std::cout << "\"" << str_trim_all << "\"" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment