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

2021-12-25 00:00:00 string replace c++

我将如何在 c++ 中执行类似于以下代码的操作:

How would I do something in c++ similar to the following code:

//Lang: Java
string.replaceAll("  ", " ");

此代码片段将用一个空格替换字符串中的所有多个空格.

This code-snippet would replace all multiple spaces in a string with a single space.

推荐答案

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::removeremove_if, std::unique 实际上并没有使容器变小,它只是将末尾的元素移动到更接近开头的位置.它返回一个迭代器到新的范围结束,因此您可以使用它来调用 erase函数,是string类的成员函数.

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.

相关文章