首页 > 代码库 > [C/C++标准库]_[初级]_[使用模板删除字符串前后空格((w)string space)]

[C/C++标准库]_[初级]_[使用模板删除字符串前后空格((w)string space)]


场景:

1. C++没有提供删除std::(w)string的前后空格的函数,比如TrimSpace.

2. 很多库都提供, 但是为了移植代码方便,最好还是能用标准库解决就用标准库.


下边用模板实现了移除空格的函数. test.cpp

#include <iostream>#include <stdlib.h>#include <string.h>#include <string>#include <ctype.h>using namespace std;//1.vc的实现> 256就崩溃.所以要自己实现inline int IsSpace(int c){    if(c == 0x20 || c == 0x09 || c== 0x0D)    {        return 1;    }    return 0;}template<class T>T RemovePreAndLastSpace(const T& str){        int length = str.size();    int i = 0,j = length -1;    while(i < length && IsSpace(str[i])){i++;}    while(j >= 0 && IsSpace(str[j])){j--;}    cout << i  << " :" << j<< endl;    if(j<i) return T();    return str.substr(i,j-i+1);}void TestWString(){    wstring wstr;    wstring wres;    wstr = L"asdfasd 990";    wres = RemovePreAndLastSpace(wstr);    wcout << "wres:[" << wres  << "]"<< endl;    wstr = L"asdfasd 990 ";    wres = RemovePreAndLastSpace(wstr);    wcout << "res:[" << wres  << "]"<< endl;    wstr = L" asdfasd 990 ";    wres = RemovePreAndLastSpace(wstr);    wcout << "res:[" << wres  << "]"<< endl;    wstr = L"";    wres = RemovePreAndLastSpace(wstr);    wcout << "res:[" << wres  << "]"<< endl;    wstr = L" ";    wres = RemovePreAndLastSpace(wstr);    wcout << "res:[" << wres  << "]"<< endl;    wstr = L"\0";    wres = RemovePreAndLastSpace(wstr);    wcout << "res:[" << wres  << "]"<< endl;}void TestString(){    string wstr;    string wres;    wstr = "asdfasd 990";    wres = RemovePreAndLastSpace(wstr);    cout << "wres:[" << wres  << "]"<< endl;    wstr = "asdfasd 990 ";    wres = RemovePreAndLastSpace(wstr);    cout << "res:[" << wres  << "]"<< endl;    wstr = " asdfasd 990 ";    wres = RemovePreAndLastSpace(wstr);    cout << "res:[" << wres  << "]"<< endl;    wstr = "";    wres = RemovePreAndLastSpace(wstr);    cout << "res:[" << wres  << "]"<< endl;    wstr = " ";    wres = RemovePreAndLastSpace(wstr);    cout << "res:[" << wres  << "]"<< endl;    wstr = "\0";    wres = RemovePreAndLastSpace(wstr);    cout << "res:[" << wres  << "]"<< endl;}int main(int argc, char const *argv[]){    TestWString();    cout << "................................." << endl;    TestString();    return 0;}

输出:

0 :10wres:[asdfasd 990]0 :10res:[asdfasd 990]1 :11res:[asdfasd 990]0 :-1res:[]1 :-1res:[]0 :-1res:[].................................0 :10wres:[asdfasd 990]0 :10res:[asdfasd 990]1 :11res:[asdfasd 990]0 :-1res:[]1 :-1res:[]0 :-1res:[]



[C/C++标准库]_[初级]_[使用模板删除字符串前后空格((w)string space)]