简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM