首页 > 文章列表 > C++程序来检查一个字符是否为字母或非字母

C++程序来检查一个字符是否为字母或非字母

C程序 字符检查 字母/非字母
426 2023-08-19

Using strings or characters is sometimes very useful while solving some logical programming problems. Strings are a collection of characters and characters are 1-byte datatype to hold symbols from ASCII values. The symbols can be letters from English alphabets, numeric digits, or special characters. In this article, we shall learn how to check whether a character is a letter in English an alphabet or not using C++.

检查 isalpha() 函数

To check whether a number is an alphabet or not, we can use the isalpha() function from the ctype.h header file. This takes a character as input and returns true when it is the alphabet, otherwise returns false. Let us see the following C++ implementation to understand the usage of this function.

Example

的中文翻译为:

示例

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

Output

Is 'K' an alphabet? : True
Is 'a' an alphabet? : True
Is '!' an alphabet? : False
Is '5' an alphabet? : False
Is 'f' an alphabet? : True

By creating our function for checking

上述方法是使用预定义函数来检查给定字符是否为字母。但是我们也可以通过定义一个带有范围条件的函数来实现相同的功能。算法如下 -

算法

  • read a character c as input
  • if ASCII of c is in range lowercase 'a' and 'z' or in range uppercase 'A' and 'Z', then
  • otherwise
  • return false
  • end if

Example

的中文翻译为:

示例

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

Output

Is 'T' an alphabet? : True
Is 'g' an alphabet? : True
Is '?' an alphabet? : False
Is '8' an alphabet? : False
Is 'p' an alphabet? : True

Conclusion

检查给定字符是否为字母,有几种不同的方法。我们讨论的第一种方法是使用ctype.h头文件中的isalpha函数。当字符是字母时,该函数返回true,否则返回false。在我们讨论的第二种方法中,我们编写了自己的函数来进行此检查。这是通过检查ASCII码是否在小写字母'a'到'z'或大写字母'A'到'Z'的给定范围内来进行的。如果是,则返回true,否则返回false。