标签:c++ string 删除前后空格 wstring 模板
场景:
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 :10 wres:[asdfasd 990] 0 :10 res:[asdfasd 990] 1 :11 res:[asdfasd 990] 0 :-1 res:[] 1 :-1 res:[] 0 :-1 res:[] ................................. 0 :10 wres:[asdfasd 990] 0 :10 res:[asdfasd 990] 1 :11 res:[asdfasd 990] 0 :-1 res:[] 1 :-1 res:[] 0 :-1 res:[]
[C/C++标准库]_[初级]_[使用模板删除字符串前后空格((w)string space)]
标签:c++ string 删除前后空格 wstring 模板
原文地址:http://blog.csdn.net/infoworld/article/details/41981639