Check if string contains any non ASCII character in C++

This tutorial will discuss about a unique way to check if string contains any non ascii character in C++.

We can use the all_of() function to check if all the characters in a string satisfies a given condition or not. To check if there is any non ASCII character in a string, we can confirm that if all the characters in the string are ASCII characters. If yes, then it means there are no non ASCII characters in the string.

For that we will pass three arguments to the all_of() function,

  • Iterator pointing to the first character of string.
  • Iterator pointing to the end of string.
  • A Lambda function, which accepts a character as an argument and checks if the ASCII value of this character is less than 128 or not. If yes then it will return true, otherwise it will return false.

So, all_of() function will apply this Lambda function on all the characters in string, and if all the return values are true, then it will return true otherwise it will return false.

If the all_of() function returns true, then it means that all the characters in string are ASCII characters.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

// Returns True, if all characters in the string
// are ASCII characters
bool isAllAscii(const std::string& str)
{
    return std::all_of(
                str.begin(),
                str.end(),
                [](const unsigned char& ch){
                    return ch <= 127;
                });
}

int main()
{

    string strValue = "Testing üString";

    // Check if all characters in string are ASCII characters
    if (isAllAscii(strValue))
    {
        cout << "Yes, all characters in string are ASCII characters" << endl;
    }
    else
    {
        cout << "No, all characters in string are not ASCII characters" << endl;
    }

    return 0;
}

Output :

No, all characters in string are not ASCII characters

Summary

Today we learned about several ways to check if string contains any non ascii character in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top