Skip to content

Instantly share code, notes, and snippets.

@letiantian
Last active June 26, 2025 04:39
Show Gist options
  • Save letiantian/a51003ae3f9896ee68d8c51f26c9312f to your computer and use it in GitHub Desktop.
Save letiantian/a51003ae3f9896ee68d8c51f26c9312f to your computer and use it in GitHub Desktop.
trim string in C++ 11
#include <iostream>
std::string trim(const std::string & source) {
std::string s(source);
s.erase(0,s.find_first_not_of(" \n\r\t"));
s.erase(s.find_last_not_of(" \n\r\t")+1);
return s;
}
int main(int argc, const char * argv[]) {
std::cout << "|" << trim("") << "|" << std::endl;
std::cout << "|" << trim(" ") << "|" << std::endl;
std::cout << "|" << trim(" \n") << "|" << std::endl;
std::cout << "|" << trim("abc") << "|" << std::endl;
std::cout << "|" << trim(" abc") << "|" << std::endl;
std::cout << "|" << trim("abc ") << "|" << std::endl;
std::cout << "|" << trim(" abc ") << "|" << std::endl;
return 0;
}
/**
||
||
||
|abc|
|abc|
|abc|
|abc|
**/
@mcordova1967
Copy link

Very nice, thank you for sharing it. Regards, Martin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment