21xrx.com
2024-09-20 00:45:40 Friday
登录
文章检索 我的文章 写文章
如何在C++中判断字母大小写
2023-06-23 18:45:46 深夜i     --     --
C++ 判断 字母 大小写

在C++中判断字母的大小写非常简单,可以使用标准库函数或者手动判断字母的ASCII码值。

方法一:使用标准库函数

C++中有一个isupper()函数和一个islower()函数,用于判断字符是否为大写字母和小写字母。这两个函数都在头文件 中声明,调用方法如下:


#include <iostream>

#include <cctype>

using namespace std;

int main() {

  char ch = 'A';

  if (isupper(ch))

    cout << "This is an uppercase letter." << endl;

   else

    cout << "This is not an uppercase letter." << endl;

  

  ch = 'c';

  if (islower(ch))

    cout << "This is a lowercase letter." << endl;

   else

    cout << "This is not a lowercase letter." << endl;

  

  return 0;

}

方法二:手动判断ASCII码值

在ASCII码表中,大写字母的ASCII码值范围是65到90,小写字母的ASCII码值范围是97到122。因此,可以使用下面的代码进行判断:


#include <iostream>

using namespace std;

int main() {

  char ch = 'A';

  if (ch >= 'A' && ch <= 'Z')

    cout << "This is an uppercase letter." << endl;

   else

    cout << "This is not an uppercase letter." << endl;

  

  ch = 'c';

  if (ch >= 'a' && ch <= 'z')

    cout << "This is a lowercase letter." << endl;

   else

    cout << "This is not a lowercase letter." << endl;

  

  return 0;

}

以上两种方法都可以判断字符是否为大写字母或小写字母,具体使用哪种方法取决于程序员的个人喜好和代码风格。无论使用哪种方法,判断字母的大小写都非常简单和方便。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复