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

后端 未结 11 1475
野的像风
野的像风 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:31

    You could always loop through and just erase all non alphanumeric characters if you're using string.

    #include 
    
    size_t i = 0;
    size_t len = str.length();
    while(i < len){
        if (!isalnum(str[i]) || str[i] == ' '){
            str.erase(i,1);
            len--;
        }else
            i++;
    }
    

    Someone better with the Standard Lib can probably do this without a loop.

    If you're using just a char buffer, you can loop through and if a character is not alphanumeric, shift all the characters after it backwards one (to overwrite the offending character):

    #include 
    
    size_t buflen = something;
    for (size_t i = 0; i < buflen; ++i)
        if (!isalnum(buf[i]) || buf[i] != ' ')
            memcpy(buf[i], buf[i + 1], --buflen - i);
    

提交回复
热议问题