且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用一个字符串中的一个空格替换多个空格

更新时间:2022-12-11 08:10:30

bool BothAreSpaces(char lhs, char rhs) { return (lhs == rhs) && (lhs == ' '); }

std::string::iterator new_end = std::unique(str.begin(), str.end(), BothAreSpaces);
str.erase(new_end, str.end());   

如何工作。 std :: unique 有两种形式。第一个表单遍历一个范围,并删除相邻的重复项。所以字符串abbaaabbbb变成abab。我使用的第二种形式,使用一个谓词,它应该接受两个元素,并返回true,如果他们应该被认为是重复的。我写的函数 BothAreSpaces 用于这个目的。它确切地确定它的名字暗示,它的参数都是空格。因此,当与 std :: unique 结合使用时,会删除重复的相邻空格。

How this works. The std::unique has two forms. The first form goes through a range and removes adjacent duplicates. So the string "abbaaabbbb" becomes "abab". The second form, which I used, takes a predicate which should take two elements and return true if they should be considered duplicates. The function I wrote, BothAreSpaces, serves this purpose. It determines exactly what it's name implies, that both of it's parameters are spaces. So when combined with std::unique, duplicate adjacent spaces are removed.

就像 std :: remove remove_if std :: unique 容器越小,它只是移动元素在结束更接近开始。它返回一个迭代器到新的结束范围,所以你可以使用它来调用擦除函数,这是字符串类的成员函数。

Just like std::remove and remove_if, std::unique doesn't actually make the container smaller, it just moves elements at the end closer to the beginning. It returns an iterator to the new end of range so you can use that to call the erase function, which is a member function of the string class.

打破它,擦除函数采用两个参数,即要删除的范围的开始和结束迭代器。对于它的第一个参数,我传递 std :: unique 的返回值,因为这是我要开始擦除的位置。对于它的第二个参数,我传递字符串的结束迭代器。

Breaking it down, the erase function takes two parameters, a begin and an end iterator for a range to erase. For it's first parameter I'm passing the return value of std::unique, because that's where I want to start erasing. For it's second parameter, I am passing the string's end iterator.