Home > OS >  Is this good enough to check an ascii string?
Is this good enough to check an ascii string?

Time:01-26

bool is_ascii(const string &word) {
   if((unsigned char)(*word.c_str()) < 128){
      return true
  }
   return false
}

I want to check whether a string is ascii string. I also saw such a function to detect whether a string is ascii chars or not:

bool is_ascii(const string &str){
         std::locale loc;
         for(size_t i = 0; i < str.size(); i  )
         if( !isalpha(str[i], loc) && !isspace(str[i], loc))
                 return false;
         return true;
 }

Which one is better or more reliable?

CodePudding user response:

ASCII is a lot more than just alpha characters and spaces. If you want to accept all ASCII, just use your second example and change the if:

if(str[i] < 0 || str[i] > 0x7f)
    return false;

CodePudding user response:

Other answers get the is-char-ASCII part already. I’m assuming it’s right. Putting it together I’d recommend:

#include <algorithm>

bool is_ascii_char(unsigned char c) {
    return c & 0x80 == 0;
}

bool is_ascii(std::string_view s) {
    return std::ranges::all_of(s, is_ascii_char);
}

Or before C 20, that could be return std::all_of(s.begin(), s.end(), is_ascii_char);.

  •  Tags:  
  • Related