programing tip

C ++ 문자열에서 문자의 모든 발생을 제거하는 방법

itbloger 2020. 9. 12. 09:14
반응형

C ++ 문자열에서 문자의 모든 발생을 제거하는 방법


다음을 사용하고 있습니다.

replace (str1.begin(), str1.end(), 'a' , '')

그러나 이것은 컴파일 오류를 제공합니다.


기본적으로 replace문자를 다른 문자로 대체하고 문자 ''가 아닙니다. 당신이 찾고있는 것은입니다 erase.

동일한 문제에 대한 답 이있는이 질문참조하십시오 . 귀하의 경우 :

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

또는 boost다음과 같은 옵션 인 경우 사용 하십시오.

#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");

이 모든 것은 참조 웹 사이트 에 잘 문서화되어 있습니다. 그러나 이러한 기능을 몰랐다면 이런 종류의 일을 손으로 쉽게 할 수 있습니다.

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];

알고리즘 std::replace주어진 시퀀스에서 요소별로 작동 합니다 (따라서 요소를 다른 요소로 대체하고 아무것도 대체 할 수 없습니다 ). 그러나 문자 가 없습니다 . 당신이 시퀀스에서 요소를 제거 할 경우, 다음과 같은 요소가 될 필요가 이동 하고, std::replace이런 식으로 작동하지 않습니다.

이를 달성하기 위해 std::remove( 와 함께std::erase )를 사용할 수 있습니다 .

str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

사용 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;
}

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;
}

이것이 내가 한 방법입니다.

또는 Antoine이 언급 한대로 할 수 있습니다.

동일한 문제에 대한 답 이있는이 질문참조하십시오 . 귀하의 경우 :

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

이 코드는 문자의 반복을 제거합니다. 즉, 입력이 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;

In case you have a predicate and/or a non empty output to fill with the filtered string, I would consider:

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';}


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:

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] = '\0';
    return string(c);
}

Just use as

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.


This is how I do it:

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;
}

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.


#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());

Will remove capital Y and S from str, leaving "ourtring".

Note that remove is an algorithm and needs the header <algorithm> included.

참고URL : https://stackoverflow.com/questions/20326356/how-to-remove-all-the-occurrences-of-a-char-in-c-string

반응형