問題描述
在 C++ 中從字符串中刪除空格的首選方法是什么?我可以遍歷所有字符并構(gòu)建一個新字符串,但有沒有更好的方法?
What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?
推薦答案
最好的做法是使用算法 remove_if
和 isspace:
The best thing to do is to use the algorithm remove_if
and isspace:
remove_if(str.begin(), str.end(), isspace);
現(xiàn)在算法本身不能改變?nèi)萜?只能修改值),所以它實際上將值打亂并返回一個指向現(xiàn)在結(jié)束位置的指針.所以我們必須調(diào)用string::erase來實際修改容器的長度:
Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
我們還應(yīng)該注意,remove_if 最多只會制作一份數(shù)據(jù)副本.這是一個示例實現(xiàn):
We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:
template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
T dest = beg;
for (T itr = beg;itr != end; ++itr)
if (!pred(*itr))
*(dest++) = *itr;
return dest;
}
這篇關(guān)于從 C++ 中的 std::string 中刪除空格的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!