本文實例講述了c++ String去除頭尾空格的方法,分享給大家供大家參考。具體實現方法如下:
實現該功能可使用string的find_first_not_of,和find_last_not_of方法,具體實現帶如下:
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;
}
希望本文所述對大家的C++程序設計有所幫助。
新聞熱點
疑難解答
圖片精選