C++中如何去掉std::string对象的首尾空格

来源:互联网 发布:最新华为抢购软件 编辑:程序博客网 时间:2024/05/16 11:11
/***********write by myself***********/
/***********begin test file***********/
#include
#include


int main()
{
std::string str1 = "   hello world!   ";
std::string trimstring = " ";
std::cout << "str = /"" << str1 << "/"" << std::endl;
std::cout << "str.find_first_of(' ')     : " << str1.find_first_of(trimstring)     << std::endl;
std::cout << "str.find_first_not_of(' ') : " << str1.find_first_not_of(trimstring) << std::endl;
std::cout << "str.find_last_of(' ')     : " << str1.find_last_of(trimstring)      << std::endl;
std::cout << "str.find_last_not_of(' ')  : " << str1.find_last_not_of(trimstring)  << std::endl;
str1.erase(str1.find_last_not_of(trimstring)+1);
std::cout << "after right trim : /"" << str1 << "/"" << std::endl;
str1.erase(0,str1.find_first_not_of(trimstring));
std::cout << "after left trim  : /"" << str1 << "/"" << std::endl;
return 0;
}
/***********end test file***********/


tstring trim(tstring& s, CONST tstring& drop)
{
    //trim right
    s.erase(s.find_last_not_of(drop)+1);
    //trim left
    return s.erase(0,s.find_first_not_of(drop));
}

原创粉丝点击