C++ 中的 isalpha()
函数用于检查给定的字符是否为字母。它定义在 cctype 头文件中。
示例
#include <iostream>
#include <cctype>
using namespace std;
int main() {
// check if '7' is an alphabet
int result = isalpha('7');
cout << result;
return 0;
}
// Output: 0
isalpha() 语法
isalpha()
的语法是:
isalpha(int ch);
这里,ch 是我们要检查的字符。
isalpha() 参数
isalpha()
函数接受以下参数:
- ch - 要检查的字符,转换为
int
或EOF
isalpha() 返回值
isalpha()
函数返回:
- 如果 ch 是字母,则返回非零值。
- 如果 ch 不是字母,则返回零。
isalpha() 函数原型
定义在 cctype 头文件中的 isalpha()
的原型是:
int isalpha(int ch);
这里,将根据当前安装的 C 语言环境分类检查 ch 是否为字母。默认情况下,以下字符是字母:
- 大写字母:
'A'
到'Z'
- 小写字母:
'a'
到'z'
isalpha() 未定义行为
如果以下情况,isalpha()
的行为是未定义的:
- 如果 ch 的值不能表示为 unsigned char,或者
- 如果 ch 的值不等于
EOF
示例:C++ isalpha()
#include <cctype>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "ad138kw+~!$%?';]qjj";
int count = 0, check;
// loop to count the no. of alphabets in str
for (int i = 0; i <= strlen(str); ++i) {
// check if str[i] is an alphabet
check = isalpha(str[i]);
// increment count if str[i] is an alphabet
if (check)
++count;
}
cout << "Number of alphabet characters: " << count << endl;
cout << "Number of non-alphabet characters: " << strlen(str) - count;
return 0;
}
输出
Number of alphabet characters: 7 Number of non alphabet characters: 12
在此程序中,我们使用了一个 for 循环和 isalpha()
函数来计算 str 中的字母数量。
此程序中使用了以下变量和代码:
strlen(str)
- 获取 str 字符串的 长度。- check - 使用
isalpha()
检查 str[i] 是否为字母。 - count - 存储 str 中的字母数量。
strlen(str) - count
- 获取 str 中非字母字符的数量。