Using strings or characters is sometimes very useful when solving some logic programming problems. A string is a collection of characters, a 1-byte data type that holds symbols in ASCII values. Symbols can be English letters, numbers, or special characters. In this article, we will learn how to check if a character is an English letter or a letter of the alphabet using C.
To check if a number is a letter, we can use the isalpha() function in the ctype.h header file. This takes a character as input and returns true if it is an alphabet, false otherwise. Let us look at the following C implementation to understand the usage of this function.
The Chinese translation of#include <iostream> #include <ctype.h> using namespace std; string solve( char c ) { if( isalpha( c ) ) { return "True"; } else { return "False"; } } int main() { cout << "Is 'K' an alphabet? : " << solve( 'K' ) << endl; cout << "Is 'a' an alphabet? : " << solve( 'a' ) << endl; cout << "Is '!' an alphabet? : " << solve( '!' ) << endl; cout << "Is '5' an alphabet? : " << solve( '5' ) << endl; cout << "Is 'f' an alphabet? : " << solve( 'f' ) << endl; }
Is 'K' an alphabet? : True Is 'a' an alphabet? : True Is '!' an alphabet? : False Is '5' an alphabet? : False Is 'f' an alphabet? : True
The above method is to use a predefined function to check whether a given character is a letter. But we can also achieve the same functionality by defining a function with range conditions. The algorithm is as follows -
#include <iostream> #include <ctype.h> using namespace std; string solve( char c ) { if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) { return "True"; } else { return "False"; } } int main() { cout << "Is 'T' an alphabet? : " << solve( 'T' ) << endl; cout << "Is 'g' an alphabet? : " << solve( 'g' ) << endl; cout << "Is '?' an alphabet? : " <<solve( '?' ) << endl; cout << "Is '8' an alphabet? : " << solve( '8' ) << endl; cout << "Is 'p' an alphabet? : " << solve( 'p' ) << endl; }
Is 'T' an alphabet? : True Is 'g' an alphabet? : True Is '?' an alphabet? : False Is '8' an alphabet? : False Is 'p' an alphabet? : True
There are several different ways to check if a given character is a letter. The first method we discussed is to use the isalpha function in the ctype.h header file. This function returns true when the character is a letter, false otherwise. In the second method we discussed, we wrote our own function to do this check. This is done by checking if the ASCII code is within a given range of lowercase letters 'a' to 'z' or uppercase letters 'A' to 'Z'. If so, it returns true, otherwise it returns false.
The above is the detailed content of C++ program to check if a character is alphabetic or non-alphabetic. For more information, please follow other related articles on the PHP Chinese website!