首页 > 代码库 > [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)]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。