C++ String trim function
#include <iostream>
#include <string>
using namespace std;
void __trim(std::string &str,bool trim_left,bool trim_right)
{
std::string::size_type begin=0;
std::string::size_type end=str.size()-1;
while(left && begin<=end && (str[begin]<=0x20 || str[begin]==0x7f))
++begin;
while(right && end>begin && (str[end]<=0x20 || str[end]==0x7f))
--end;
str = str.substr(begin, end - begin + 1);
}
void trim(std::string &str) { __trim(str,1,1); }
void ltrim(std::string &str) { __trim(str,1,0); }
void rtrim(std::string &str) { __trim(str,0,1); }
int main(int argc, char **argv)
{
string v1 = " \n\r\tALPHA\r\t\n ";
trim(v1);
string v2 = " \n\r\tALPHA\r\t\n ";
ltrim(v2);
string v3 = " \n\r\tALPHA\r\t\n ";
rtrim(v3);
cout << "|" << v1 << "|" << endl;
cout << "|" << v2 << "|" << endl;
cout << "|" << v3 << "|" << endl;
return 0;
}code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)
|