如何在C语言中仅统计字符串中的句号(.)?
仅统计字符串中句号的实现方法
方法一:直接匹配目标字符(推荐)
既然你的需求只是统计句号(.),完全不需要用到ispunct函数——直接判断字符是否等于.就够了,逻辑简单且高效,还能避免误统计其他标点。
示例代码:
#include <stdio.h> int count_periods(const char *str) { int count = 0; while (*str != '\0') { if (*str == '.') { count++; } str++; } return count; } int main() { const char *test_str = "Hello, world! This is a test. Another sentence here."; printf("句号数量:%d\n", count_periods(test_str)); return 0; }
方法二:基于ispunct做额外过滤(仅适合特定场景)
如果一定要保留ispunct的使用,你可以在判断为标点的基础上,额外排除逗号(,)和感叹号(!)。但要注意:如果字符串中存在其他标点(比如分号、问号),这种方法会把它们也统计进去,所以只适合字符串里只有句号、逗号、感叹号三种标点的场景。
示例代码:
#include <stdio.h> #include <ctype.h> int count_periods(const char *str) { int count = 0; while (*str != '\0') { // 先判断是标点,再排除逗号和感叹号 if (ispunct((unsigned char)*str) && *str != ',' && *str != '!') { count++; } str++; } return count; } int main() { const char *test_str = "Hello, world! This is a test. Another sentence here."; printf("句号数量:%d\n", count_periods(test_str)); return 0; }
总结
优先选择方法一,因为它完全贴合你的需求,没有多余的判断逻辑,也不会出现误统计的情况。
内容的提问来源于stack exchange,提问作者user22869055
相关产品推荐
相关产品推荐

