c - 计算c中的单个字符
问题描述
我正在研究一个名为可读性的项目。用户输入文本,然后代码应使用 coleman-liau 函数来确定阅读水平。但是为了使用这个函数,你必须确定单词、字母和句子的数量。现在我正忙着数字母。所以我想问如何计算c中的单个字符。现在这是我的代码:
int count_letters (string text)
{
int count_letters = 0;
int numb = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (text[i] != '')
{
count_letters++;
}
}
return count_letters;
}
解决方案
您可以使用isalpha()
或“即兴创作”。
这将适用于ASCII字符集:
#include <stdio.h>
int count_letters(const char *str)
{
int count = 0, i = 0;
for (; str[i] != '\0'; i++)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
/* any character within this range is either a lower or upper case letter */
count++;
}
}
return count;
}
int main(void)
{
char *str = "Hello\n world hello123@";
printf("%d\n", count_letters(str));
return 0;
}
或 use isalpha()
,也支持您当前的语言环境。
#include <ctype.h>
int count_letters(const char *str)
{
int count = 0, i = 0;
for (; str[i] != '\0'; i++)
{
if (isalpha((unsigned char)str[i]))
{
count++;
}
}
return count;
}
编辑:正如Andrew所提到的,要迂腐,你最好传递一个unsigned char
as 参数来isalpha()
避免由于str
.
推荐阅读
- websocket - 如何使用 Absinthe (Elixir) 和 Urql 进行 graphql 订阅?
- xml - 读取 XML 并存储在变量、ASMX、VB.NET 中
- c# - Selenium c# System.InvalidOperationException: '会话未创建'
- flutter - 带有放大和缩小选项的颤振扫描二维码
- python - 在方法中将字符串传递给 eval
- python - 使用 Pandas 访问 Python 中的列
- notifications - FHIR 管理通知
- visual-studio - Azure DevOps Server 升级期间无法删除弹性搜索服务
- python - 使用正则表达式逐行解析没有分隔符的文本
- python - 如何使用 URL 从数据库中检索数据