在C ++中从std :: string中删除空格 [英] Remove spaces from std::string in C++
问题描述
在C ++中,从字符串中删除空格的首选方法是什么?我可以循环遍历所有的字符,并建立一个新的字符串,但有更好的方法吗?
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);
现在算法本身不能更改容器(只修改值),所以实际上是shuffle值周围的值并返回一个指针,指向现在应该结束的位置。所以我们必须调用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());
我们还应该注意,remove_if最多只能创建一个数据副本。这里是一个示例实现:
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;
}
这篇关于在C ++中从std :: string中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!