C语言统计字符串运算符及SIN/COS次数失效,如何修复并扩展?
问题根因
- 函数使用错误:
strchr的作用是查找单个字符在字符串中的首次出现位置,代码中传入多字符常量'SIN'/'COS'属于完全错误的用法,之前SIN统计逻辑看似正常属于巧合,实际匹配依赖的是后续的strstr调用,判断条件的错误被侥幸绕过。 - 循环逻辑冗余:代码中定义的
check变量未被修改,do-while循环的判断条件完全失效,仅靠break跳出循环,逻辑可读性极差。 - 误统计风险:当前匹配逻辑未校验关键词边界,会把
sine、sin_e这类包含关键词前缀的字符串误统计为有效关键词。 - 资源浪费:不需要为每个关键词单独拷贝原字符串,单份字符串副本即可完成所有统计逻辑。
修复代码
#include <stdio.h> #include <string.h> #include <ctype.h> // 通用关键词统计函数,支持边界校验避免误统计 int count_keyword(const char *str, const char *keyword) { int count = 0; int kw_len = strlen(keyword); const char *cur = str; while ((cur = strstr(cur, keyword)) != NULL) { // 校验边界:关键词前后不能是字母,避免把sine里的sin算进去 int left_valid = (cur == str) || (!isalpha(*(cur - 1))); int right_valid = (!isalpha(*(cur + kw_len))); if (left_valid && right_valid) { count++; } cur += kw_len; // 跳过当前关键词,继续向后查找 } return count; } int main() { int count = 0; char buff[100] = "1+2.3(7^8)sin cos + cos sin_e-2x+x2*2!/_x1 sine"; // 转大写,统一匹配规则(替代非标准C函数strupr) for (int i = 0; buff[i] != '\0'; i++) { buff[i] = toupper(buff[i]); } // 统计运算符 for (int i = 0; buff[i] != '\0'; i++) { if (buff[i] == '+' || buff[i] == '-' || buff[i] == '*' || buff[i] == '/' || buff[i] == '^'|| buff[i] == '(') { count++; } } // 统计关键词,需要新增只要加数组元素即可 const char *keywords[] = {"SIN", "COS", NULL}; for (int i = 0; keywords[i] != NULL; i++) { count += count_keyword(buff, keywords[i]); } printf("FINAL \n%d", count); return 0; }
扩展支持更多关键词的方法
只需要在keywords数组中新增需要统计的关键词大写字符串即可,不需要修改统计逻辑,比如要增加TAN、LOG的统计,直接修改数组为:
const char *keywords[] = {"SIN", "COS", "TAN", "LOG", NULL};
如果不需要边界校验(允许匹配前缀),直接删除count_keyword函数中的边界判断逻辑即可。
内容的提问来源于stack exchange,提问作者Jack Savage
相关产品推荐
相关产品推荐

