How to strip all non alphanumeric characters from a string in c++?

后端 未结 11 1439
野的像风
野的像风 2020-11-30 02:07

I am writing a piece of software, and It require me to handle data I get from a webpage with libcurl. When I get the data, for some reason it has extra line breaks in it. I

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 02:25

    #include 
    #include 
    #include 
    
    std::string s = "Hello World!";
    s.erase(std::remove_if(s.begin(), s.end(),
        std::not1(std::ptr_fun(std::isalnum)), s.end()), s.end());
    std::cout << s << std::endl;
    

    Results in:

    "HelloWorld"
    

    You use isalnum to determine whether or not each character is alpha numeric, then use ptr_fun to pass the function to not1 which NOTs the returned value, leaving you with only the alphanumeric stuff you want.

提交回复
热议问题