如何将字符串前后的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++)
2008-07-05 22:24
711 查看
1/**//* 2(C) OOMusou 2006 http://oomusou.cnblogs.com 3 4Filename : StringTrim1.cpp 5Compiler : Visual C++ 8.0 6Description : Demo how to trim string by find_first_not_of & find_last_not_of 7Release : 11/17/2006 8*/ 9#include <iostream> 10#include <string> 11 12std::string& trim(std::string &); 13 14int main() { 15 std::string s = " Hello World!! "; 16 std::cout << s << " size:" << s.size() << std::endl; 17 std::cout << trim(s) << " size:" << trim(s).size() << std::endl; 18 19 return 0; 20} 21 22std::string& trim(std::string &s) { 23 if (s.empty()) { 24 return s; 25 } 26 27 s.erase(0,s.find_first_not_of(" ")); 28 s.erase(s.find_last_not_of(" ") + 1); 29 return s; 30} 31
这在字符串处理是很常用的功能,.NET Framework的String class直接提供Trim()的method,其它语言也大都有提供(VB、VFP),但C++无论Standard Library或STL都找不到相对应方法,以下的方式是由希冀blog中的C++中如何去掉std::string对象的首尾空格 改编而来,加上了pass by reference适合function使用,其中std::string所提供的find_first_not_of()和find_last_not_of()真是大开眼界,竟然还有这种method,可以找寻第一个不符合条件的位置,我在其它语言都还没见过这样的function。
相关文章推荐
- (原創) 如何将字符串前后的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++)
- (转帖)如何将字符串前后的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++)
- 字符串处理函数find_first_of和find_last_of的使用
- std::string 类中find_first_not_of ()函数
- string中的find(),find_first_of(),find_first_not_of()之间区别
- std::string::find_last_not_of
- string 中的 find()、 find_first_of()、find_first_not_of()
- std :: string :: find_first_not_of
- C++ 标准模板库学习之 string 类 详解 (一) 将一个句子中每个单词的单词字母顺序翻转 关于npos find_first_not_of find_first_of getline
- (原創) 如何使用find_first_of() algorithm? (C/C++) (STL)
- string 中find_last_of的索引是字符串最后的字符,不是开始的字符的位置,记录一下
- 如何使用find_first_of() algorithm?
- string 类成员函数 find() / find_first_of() / find_last_of() 的用法详解
- 如何将字符串前后的空白去除(C/C++) (STL)
- 20170604_string中的函数find_first_of()和 find_last_of()
- (原創) 如何将字符串前后的空白去除? (C/C++) (STL)
- C++基础---string类的find/find_first_of/find_first_not_of/rfind/find_last_of/find_last_not_of
- string c++详解 find_first_not_of() find_first_of()
- Spring Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(Can not deserialize value of type Date from String)
- string类find_first_not_of ()方法