Trim a string with C++ demo code following:
// TrimStringDemo.cpp
#include <iostream>
#include <string>
using namespace std;
string LTrimString(const string str)
{
int h = 0, t = str.size();
while (h < t && (str[h] == ' ' || str[h] == '\t')) h++;
return str.substr(h, t - h);
}
string RTrimString(const string str)
{
int h = 0, t = str.size();
// trim right
while (h < t && (str[t-1] == ' ' || str[t-1] == '\t')) t--;
return str.substr(h, t - h);
}
// TrimeString for string including ' ', '\t'.
//
// @param [in] str -- any string
//
// BEGIN: OLD IMPLEMENTS
// string TrimString(const string str)
// {
// int h = 0, t = str.size();
//
// // trim left
// while (h < t && (str[h] == ' ' || str[h] == '\t')) h++;
//
// // trim right
// while (h < t && (str[t-1] == ' ' || str[t-1] == '\t')) t--;
//
// return str.substr(h, t - h);
// }
// END: OLD IMPLEMENTS
string TrimString(const string str) {
return RTrimString(LTrimString(str));
}
#define TEST_ISO_BEGIN() \
string iso;
#define TEST_ISO(_iso_) \
iso = _iso_; \
cout << "LTrim: '" << iso << "'" << " -> |" << LTrimString(iso) << "|" << endl; \
cout << "RTrim: '" << iso << "'" << " -> |" << RTrimString(iso) << "|" << endl; \
cout << "BTrim: '" << iso << "'" << " -> |" << TrimString(iso) << "|" << endl; \
cout << endl;
int main(int argc, char **argv) {
TEST_ISO_BEGIN();
TEST_ISO(" ");
TEST_ISO(" GBR ");
TEST_ISO(" GBR");
TEST_ISO("GBR ");
TEST_ISO(" GBR ");
TEST_ISO(" GBR ");
TEST_ISO(" G B R\t\t\t\t ");
return 0;
}
Output:
$./demo
LTrim: ' ' -> ||
RTrim: ' ' -> ||
BTrim: ' ' -> ||
LTrim: ' GBR ' -> |GBR |
RTrim: ' GBR ' -> | GBR|
BTrim: ' GBR ' -> |GBR|
LTrim: ' GBR' -> |GBR|
RTrim: ' GBR' -> | GBR|
BTrim: ' GBR' -> |GBR|
LTrim: 'GBR ' -> |GBR |
RTrim: 'GBR ' -> |GBR|
BTrim: 'GBR ' -> |GBR|
LTrim: ' GBR ' -> |GBR |
RTrim: ' GBR ' -> | GBR|
BTrim: ' GBR ' -> |GBR|
LTrim: ' GBR ' -> |GBR |
RTrim: ' GBR ' -> | GBR|
BTrim: ' GBR ' -> |GBR|
LTrim: ' G B R ' -> |G B R |
RTrim: ' G B R ' -> | G B R|
BTrim: ' G B R ' -> |G B R|