Last active
May 31, 2021 18:08
-
-
Save dedeexe/9080526 to your computer and use it in GitHub Desktop.
Trimming string in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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