去除字符串首尾空格
方法1:
function trim(str){
return str.replace(/(^\s*)|(\s*$)/g, "");
}
return str.replace(/(^\s*)|(\s*$)/g, "");
}
方法2:
int main()
{
std::string str = " hello world! ";
std::string trimstring = " ";
str.erase(str.find_last_not_of(trimstring)+1);
{
std::string str = " hello world! ";
std::string trimstring = " ";
str.erase(str.find_last_not_of(trimstring)+1);
std::cout << "after right trim: " << str << “end” << std::endl; //输出"end"便于测试
str.erase(0,str.find_first_not_of(trimstring));
std::cout << "after left trim: " << str << std::endl;
return 0;
}
str.erase(0,str.find_first_not_of(trimstring));
std::cout << "after left trim: " << str << std::endl;
return 0;
}
//写成函数的形式
string trim(string& s, CONST string& drop)
{
//trim right
s.erase(s.find_last_not_of(drop)+1);
//trim left
return s.erase(0,s.find_first_not_of(drop));
}
{
//trim right
s.erase(s.find_last_not_of(drop)+1);
//trim left
return s.erase(0,s.find_first_not_of(drop));
}