c++:std::find_if使用,删除字符串空白字符串

方法

void trimLeft(std::string& str)
{
    str.erase(str.begin(),std::find_if(str.begin(),str.end(),[](char ch)->bool{if(isspace(ch)){return false;}return true;}));
}

void trimRight(std::string& str)
{
    str.erase(std::find_if(str.begin(),str.end(),[](char ch)->bool{if(isspace(ch)){return true;}return false;}),str.end());
}

void trim(string &str)
{
    trimLeft(str);
    trimRight(str);
}

测试

    std::string str1{"\n\t abc  "};
    std::cout<<str1<<" "<<str1.size()<<std::endl;
    trimLeft(str1);
    std::cout<<str1<<" "<<str1.size()<<std::endl;
   

 trimRight(str1);
    std::cout<<str1<<" "<<str1.size()<<std::endl;

全部

   trim(str1);
  std::cout<<str1<<" "<<str1.size()<<std::endl;

你可能感兴趣的:(C++11,c++,算法,开发语言)