📅  最后修改于: 2023-12-03 15:05:23.126000             🧑  作者: Mango
当我们处理字符串时,经常需要判断某个字符是否为字母或数字。在C++中,可以通过isalpha()
和isdigit()
函数来实现。这两个函数都属于<cctype>
头文件。
isalpha()
函数用于判断一个字符是否为字母。当参数c为字母时,返回非0值(真),否则返回0值(假)。
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char c = 'A';
if (isalpha(c))
cout << c << " is a letter." << endl;
else
cout << c << " is not a letter." << endl;
return 0;
}
输出:
A is a letter.
isdigit()
函数用于判断一个字符是否为数字。当参数c为数字0-9之间的字符时,返回非0值(真),否则返回0值(假)。
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char c = '5';
if (isdigit(c))
cout << c << " is a number." << endl;
else
cout << c << " is not a number." << endl;
return 0;
}
输出:
5 is a number.
isalpha()
和isdigit()
函数会返回假,因此需要确保参数为无符号字符。isalpha()
函数进行判断,因为它的匹配范围更广。#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char c = '5';
if (isalpha(c))
cout << c << " is a letter." << endl;
else if (isdigit(c))
cout << c << " is a number." << endl;
else
cout << c << " is not a letter or a number." << endl;
return 0;
}
输出:
5 is a number.