【C++】去除字符串string中的空格(兩頭空格、所有空格)

去除首尾空格:

std::string& trim(std::string &s) 
{
    if (!s.empty()) 
    {
        s.erase(0,s.find_first_not_of(" "));
    	s.erase(s.find_last_not_of(" ") + 1);
    }
    return s;
}

去除所有空格:

void trim(string &s)
{
	int index = 0;
	if(!s.empty())
	{
		while( (index = s.find(' ',index)) != string::npos)
		{
			s.erase(index,1);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章