c++测试字符的类型

本文介绍了C++中cctype头文件提供的字符操作函数,如isalpha、isdigit、isalnum等,以及tolower和toupper用于字符大小写的转换和示例程序。
摘要由CSDN通过智能技术生成

在 C++ 中,cctype 头文件提供了一组函数,用于在字符级别上进行操作。这些函数通常用于测试字符的类型或对字符进行转换。

以下是 cctype 头文件中常用的函数和其功能:

  1. isalpha(int c) 检查字符是否为字母(a-z 或 A-Z)。
  2. isdigit(int c) 检查字符是否为数字(0-9)。
  3. isalnum(int c) 检查字符是否为字母或数字。
  4. islower(int c) 检查字符是否为小写字母。
  5. isupper(int c) 检查字符是否为大写字母。
  6. tolower(int c) 如果字符是大写字母,则将其转换为小写字母;否则返回原字符。
  7. toupper(int c) 如果字符是小写字母,则将其转换为大写字母;否则返回原字符。
  8. isspace(int c) 检查字符是否为空白字符(空格、制表符、换行符等)。
#include <iostream>
#include <cctype>

int main() {
    char ch = 'A';

    if (isalpha(ch)) {
        std::cout << "The character is alphabetic." << std::endl;
    }

    if (isdigit(ch)) {
        std::cout << "The character is a digit." << std::endl;
    }

    if (isupper(ch)) {
        std::cout << "The character is uppercase." << std::endl;
    } else if (islower(ch)) {
        std::cout << "The character is lowercase." << std::endl;
    }

    // 将字符转换为小写
    char lowercaseCh = std::tolower(ch);
    std::cout << "Lowercase of '" << ch << "' is '" << lowercaseCh << "'" << std::endl;

    char ch2 = 'a';
    // 将字符转换为大写
    char uppercaseCh = std::toupper(ch2);
    std::cout << "Uppercase of '" << ch2 << "' is '" << uppercaseCh << "'" << std::endl;

    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值