'Is this good enough to check an ascii string?

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?

c++


Solution 1:[1]

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

https://godbolt.org/z/nKb673vaM

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1