Check if a string contains a non-alphanumeric character

James Warner picture James Warner · Jan 13, 2013 · Viewed 10.9k times · Source

I am trying to write a function which takes a string as an argument and checks if that string contains only one non-alphanumeric character, if this is the case then return true, if not, return false.

For example:

'Alex's' would return true. 
James..Warner would return false.

My current code is below, but I don't feel that its working. As I have a count elsewhere which basically counts the true's. Done using a map which contains the strings. And the value which I am getting for the count is too high for the words that are being input.

bool Class3::filter(string word)
    {
        string s = word;
        int len = s.size();

        for (int i=0; i<len; i++)
        {   if(!isalnum(s[i])){
            return true;}
            else{return false;}  
        }
     }

Answer

Rapptz picture Rapptz · Jan 13, 2013

You can use std::count_if and then check if the value is greater than 1.

int i = std::count_if(str.begin(),str.end(),[](char c){ return !(std::isalnum(c)); });
return i > 1;