C++ 如何删除c ++字符串中所有出现的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20326356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all the occurrences of a char in c++ string
提问by Devesh Agrawal
I am using following:
我正在使用以下内容:
replace (str1.begin(), str1.end(), 'a' , '')
But this is giving compilation error.
但这会导致编译错误。
回答by Antoine
Basically, replace
replaces a character with another and ''
is not a character. What you're looking for is erase
.
基本上,replace
用另一个字符替换一个字符,而''
不是一个字符。你要找的是erase
.
See this questionwhich answers the same problem. In your case:
看到这个问题,它回答了同样的问题。在你的情况下:
#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
Or use boost
if that's an option for you, like:
或者,boost
如果这是您的选择,请使用,例如:
#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
All of this is well-documented on referencewebsites. But if you didn't know of these functions, you could easily do this kind of things by hand:
所有这些都在参考网站上有详细记录。但是如果你不知道这些功能,你可以很容易地手工完成这种事情:
std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
if(str[i] != 'a') output += str[i];
回答by leemes
The algorithm std::replace
works per elementon a given sequence (so it replaces elements with different elements, and can not replace it with nothing). But there is no emptycharacter. If you want to remove elements from a sequence, the following elements have to be moved, and std::replace
doesn't work like this.
该算法在给定序列上按元素std::replace
工作(因此它用不同的元素替换元素,并且不能用nothing替换它)。但是没有空字符。如果要从序列中删除元素,则必须移动以下元素,并且不能像这样工作。std::replace
You can try to use std::remove
(together with std::erase
) to achieve this.
您可以尝试使用std::remove
( withstd::erase
) 来实现这一点。
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
回答by perreal
Using copy_if
:
使用copy_if
:
#include <string>
#include <iostream>
#include <algorithm>
int main() {
std::string s1 = "a1a2b3c4a5";
char s2[256];
std::copy_if(s1.begin(), s1.end(), s2, [](char c){return c!='a';});
std::cout << s2 << std::endl;
return 0;
}
回答by Rafael Valle
string RemoveChar(string str, char c)
{
string result;
for (size_t i = 0; i < str.size(); i++)
{
char currentChar = str[i];
if (currentChar != c)
result += currentChar;
}
return result;
}
This is how I did it.
我就是这样做的。
Or you could do as Antoine mentioned:
或者你可以像 Antoine 提到的那样做:
See this questionwhich answers the same problem. In your case:
#include <algorithm> str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
看到这个问题,它回答了同样的问题。在你的情况下:
#include <algorithm> str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
回答by jimifiki
In case you have a predicate
and/or a non empty output
to fill with the filtered string, I would consider:
如果您有一个predicate
和/或一个非空output
来填充过滤后的字符串,我会考虑:
output.reserve(str.size() + output.size());
std::copy_if(str.cbegin(),
str.cend(),
std::back_inserter(output),
predicate});
In the original question the predicate is [](char c){return c != 'a';}
在原始问题中,谓词是 [](char c){return c != 'a';}
回答by shivakrishna9
This code removes repetition of charecters i.e, if the input is aaabbcc then the output will be abc.
此代码删除了重复字符,即,如果输入是 aaabbcc,则输出将是 abc。
cin >> s;
ans = "";
ans += s[0];
for(int i = 1;i < s.length();++i)
if(s[i] != s[i-1])
ans += s[i];
cout << ans << endl;
回答by Raphael Silva
Based on other answers, here goes one more example where I removed all special chars in a given string:
根据其他答案,这里再举一个例子,我删除了给定字符串中的所有特殊字符:
#include <iostream>
#include <string>
#include <algorithm>
std::string chars(".,?!.:;_,!'\"-");
int main(int argc, char const *argv){
std::string input("oi?");
std::string output = eraseSpecialChars(input);
return 0;
}
std::string eraseSpecialChars(std::string str){
std::string newStr;
newStr.assign(str);
for(int i = 0; i < str.length(); i++){
for(int j = 0; j < chars.length(); j++ ){
if(str.at(i) == chars.at(j)){
char c = str.at(i);
newStr.erase(std::remove(newStr.begin(), newStr.end(), c), newStr.end());
}
}
}
return newStr;
}
Input vs Output:
输入与输出:
Input:ra,..pha
Output:rapha
Input:ovo,
Output:ovo
Input:a.vo
Output:avo
Input:oi?
Output:oi
回答by Damien
I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:
我猜 std:remove 方法有效,但它给包含的一些兼容性问题,所以我最终编写了这个小函数:
string removeCharsFromString(const string str, char* charsToRemove )
{
char c[str.length()+1]; // + terminating char
const char *p = str.c_str();
unsigned int z=0, size = str.length();
unsigned int x;
bool rem=false;
for(x=0; x<size; x++)
{
rem = false;
for (unsigned int i = 0; charsToRemove[i] != 0; i++)
{
if (charsToRemove[i] == p[x])
{
rem = true;
break;
}
}
if (rem == false) c[z++] = p[x];
}
c[z] = 'std::string removeAll(std::string str, char c) {
size_t offset = 0;
size_t size = str.size();
size_t i = 0;
while (i < size - offset) {
if (str[i + offset] == c) {
offset++;
}
if (offset != 0) {
str[i] = str[i + offset];
}
i++;
}
str.resize(size - offset);
return str;
}
';
return string(c);
}
Just use as
只需用作
myString = removeCharsFromString(myString, "abc\r");
myString = removeCharsFromString(myString, "abc\r");
and it will remove all the occurrence of the given char list.
它将删除所有出现的给定字符列表。
This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.
当循环在第一次匹配后返回时,这也可能更有效,因此我们实际上进行的比较较少。
回答by Ricardo Pieper
This is how I do it:
这就是我的做法:
#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.
基本上每当我找到给定的字符时,我都会提前偏移并将字符重新定位到正确的索引。我不知道这是否正确或有效,我(又一次)从 C++ 开始,我很感激任何对此的投入。
回答by Henno
Will remove capital Y and S from str, leaving "ourtring".
将从 str 中删除大写 Y 和 S,留下“ourtring”。
Note that remove
is an algorithm and needs the header <algorithm>
included.
请注意,这remove
是一种算法,需要<algorithm>
包含标头。