用一个字符串中的一个空格替换多个空格 [英] Replace multiple spaces with one space in a string

查看:192
本文介绍了用一个字符串中的一个空格替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在c ++中做这样的事情(java) string.replaceAll(,)

How would I do something like this (java) string.replaceAll(" ", " ") in c++

这将使得所有多个空格只是一个空格。

this would make it so that all multiple spaces become just one 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 :: 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.

这篇关于用一个字符串中的一个空格替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆