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,
Pointers in C/C++ [Full Course]
#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 :
Frequently Asked:
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.