C++中如何去掉std::string对象的首尾空格,其中std::string所提供的find_first_not_of()和find_last_not_of()帮了个大忙,这种方法可以找寻第一个不符合条件的位置。
find_first_not_of()
语法:
size_type find_first_not_of( const basic_string &str, size_type index = 0 );
size_type find_first_not_of( const char *str, size_type index = 0 );
size_type find_first_not_of( const char *str, size_type index, size_type num );
size_type find_first_not_of( char ch, size_type index = 0 );
find_first_not_of()函数:
在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops
在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始,最多查找num个字符。如果没找到就返回
例1
/*
Filename : StringTrim1.cpp
Compiler : Visual C++ 8.0
Description : Demo how to trim string by find_first_not_of & find_last_not_of
*/
#include <iostream>
#include <string>
std::string& trim(std::string &);
int main()
{
std::string s = " Hello World!! ";
std::cout << s << " size:" << s.size() << std::endl;
std::cout << trim(s) << " size:" << trim(s).size() << std::endl;
return 0;
}
std::string& trim(std::string &s)
{
if (s.empty())
{
return s;
}
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
例2
string TRIM(const string& s)
{
string::size_type head = s.find_first_not_of(" \t\n");
return ( string::npos == head ? "" : s.substr(head, s.find_last_not_of(" \t\n") -head + 1) );
}
例3
#include <string>
#include <iostream>
using namespace std;
int main()
{
string strFirst ( "abced" ),strSecond("abc abc abd def");
cout<<strFirst.find("a")<<endl;//输出结果为0,说明a当前的索引位置为0
//函数原型:size_type find_first_not_of( Char ch, size_type index = 0 ) const;
//返回在字符串中首次不匹配 d 的首字符索引,从2开始。
cout<<strFirst.find_first_not_of ( "d" ,2)<<endl; //输出结果为 2
cout<<strSecond.length()<<endl;//输出结果为15
cout<<strSecond.find_first_not_of("abc",4)<<endl; //输出结果为7
system("pause");
}