Jannat Arora
Jannat Arora

Reputation: 2989

deleting characters in C++ string

I have strings of the following form in C++

   string variable1="This is stackoverflow \"Here we go "1234" \u1234 ABC";

Now in this string I want to delete all characters except alphabets(From a to b, and A to B) and numbers. So that my output becomes

   variable1="This is stackoverflow Here we go 1234 u1234 ABC";

I tried to check for each and every character using pointers but found it very inefficient. Is there an efficient way to achieve the same using C++/C?

Upvotes: 0

Views: 272

Answers (2)

shivakumar
shivakumar

Reputation: 3407

working code example: http://ideone.com/5jxPR5

bool predicate(char ch)
    {
     return !std::isalnum(ch);
    }

int main() {
    // your code goes here


    std::string str = "This is stackoverflow Here we go1234 1234 ABC";

    str.erase(std::remove_if(str.begin(), str.end(), predicate), str.end());
    cout<<str;
    return 0;
}

Upvotes: 2

user1804599
user1804599

Reputation:

Use std::remove_if:

#include <algorithm>
#include <cctype>

variable1.erase(
    std::remove_if(
        variable1.begin(),
        variable1.end(),
        [] (char c) { return !std::isalnum(c) && !std::isspace(c); }
    ),
    variable1.end()
);

Note that the behaviors of std::isalnum and std::isspace depend on the current locale.

Upvotes: 7

Related Questions