c - 实施 isalpha 时遇到问题
问题描述
我一直在研究 CS50 中的可读性问题。第一步是创建一种只计算字母字符的方法。它建议使用该isalpha
功能,但并没有真正包括如何实现它的说明。
下面是我的代码,它成功地计算了总字母字符,但未能过滤掉标点符号、空格和整数。
谁能指出我一个更好的方向来实现isalpha
它以使其发挥作用?
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string s = get_string ("Text: \n"); // Ask for text
// Loop through the string one character at a time. Count strlen in variable n.
for (int i = 0, n = strlen(s); i < 1; i++)
// Count only the alphabetical chars.
{
while (isalpha (n)) i++;
printf ("%i", n );
}
printf("\n");
}
解决方案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
const char* s = get_string ("Text: \n");
int count = 0;
while(*s) count += !!isalpha(*s++);
printf ("%d\n", count );
return 0;
}
推荐阅读
- mongodb - mongo-express 没有连接到 mongodb
- permissions - Graph api GET group/planner/plan 由于权限而失败。这个流程最近一直有效。这有什么变化吗?
- c++ - 使用 SublimeText3 编译多个 C++ 文件
- ruby - 如何有效输入以匹配 CSV 文件中的数据
- php - 错误消息“此路由不支持 GET 方法。支持的方法:POST”
- c - 分段错误:使用双指针动态分配矩阵
- laravel - Composer git 存储库未从我的包中安装(对于 Laravel)
- python - 从 jpg、jpeg 或 png 制作缩略图
- sql - 删除或更改 ETL 2 中的记录
- r - 什么是找到数据集与参考(更大)数据集的最接近时间的有效编程方法