今天武林小編將在本文中為大家介紹c++ String去除頭尾空格的方法,相信很多小伙伴們在學習C++的時候都不知道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++ String如何去除頭尾空格的內容,本文的方法是非常簡單實用的哦,請大家務必要掌握!
新聞熱點
疑難解答
圖片精選