如何用C语言循环比较目标字符串与其他字符串并统计字符差异
C语言实现字符串对比统计:错误、多余、缺失字符数
现有代码的问题
strcmp的返回值是字符串比较的差值(第一个不同字符的ASCII差,或0表示相等),不是字符位置,用k > Value判断完全错误printf("%d", &k)输出的是变量k的内存地址,不是k的数值,应改为printf("%d", k)- 循环条件
k < OtherWords[WORDSIZE]逻辑错误,OtherWords[WORDSIZE]是数组第WORDSIZE个元素的字符值,不是字符串长度,需用strlen(OtherWords)获取有效长度 - 整体逻辑未覆盖「错误、多余、缺失字符」的统计需求
解决方案代码
方案1:按位置对比(适合严格位置匹配场景)
统计规则:
- 错误字符数:相同位置上字符不同的数量
- 多余字符数:其他字符串比目标字符串长的部分长度
- 缺失字符数:其他字符串比目标字符串短的部分长度
#include <stdio.h> #include <string.h> #define WORDSIZE 100 // 定义最大字符串长度 int main() { char target[] = "apple"; // 目标字符串 char other_words[][WORDSIZE] = {"apples", "appl", "apxle", "apple", "appla"}; // 待比较字符串数组 int num_words = sizeof(other_words) / sizeof(other_words[0]); for (int i = 0; i < num_words; i++) { char *other = other_words[i]; int len_target = strlen(target); int len_other = strlen(other); int errors = 0; int extra = 0; int missing = 0; // 统计相同长度部分的错误字符 int min_len = len_target < len_other ? len_target : len_other; for (int k = 0; k < min_len; k++) { if (target[k] != other[k]) { errors++; } } // 统计多余和缺失字符 if (len_other > len_target) { extra = len_other - len_target; } else if (len_target > len_other) { missing = len_target - len_other; } // 输出结果 printf("对比字符串:%s\n", other); if (errors == 0 && extra == 0 && missing == 0) { printf(" 完全匹配\n"); } else { printf(" 错误字符数:%d\n", errors); printf(" 多余字符数:%d\n", extra); printf(" 缺失字符数:%d\n", missing); } printf("-------------------------\n"); } return 0; }
方案2:按字符频率统计(适合不关注位置的场景)
统计规则:
- 错误字符数:其他字符串中存在但目标字符串没有的字符数量
- 多余字符数:其他字符串中字符出现次数超过目标的总和
- 缺失字符数:目标字符串中字符出现次数超过其他的总和
#include <stdio.h> #include <string.h> #define ASCII_SIZE 256 void count_chars(const char *str, int freq[]) { // 初始化频率数组 memset(freq, 0, ASCII_SIZE * sizeof(int)); while (*str != '\0') { freq[(unsigned char)*str]++; str++; } } int main() { char target[] = "apple"; char other_words[][100] = {"apples", "appl", "apxle", "apple", "aaple"}; int num_words = sizeof(other_words) / sizeof(other_words[0]); int target_freq[ASCII_SIZE]; count_chars(target, target_freq); for (int i = 0; i < num_words; i++) { char *other = other_words[i]; int other_freq[ASCII_SIZE]; count_chars(other, other_freq); int errors = 0; int extra = 0; int missing = 0; for (int c = 0; c < ASCII_SIZE; c++) { if (other_freq[c] > 0 && target_freq[c] == 0) { // 其他字符串有但目标没有的字符,算错误 errors += other_freq[c]; } else if (other_freq[c] > target_freq[c]) { // 出现次数超过目标,算多余 extra += other_freq[c] - target_freq[c]; } else if (target_freq[c] > other_freq[c]) { // 出现次数少于目标,算缺失 missing += target_freq[c] - other_freq[c]; } } printf("对比字符串:%s\n", other); if (errors == 0 && extra == 0 && missing == 0) { printf(" 完全匹配\n"); } else { printf(" 错误字符数:%d\n", errors); printf(" 多余字符数:%d\n", extra); printf(" 缺失字符数:%d\n", missing); } printf("-------------------------\n"); } return 0; }
代码说明
- 方案1适合密码验证、固定格式字符串检查等需要严格位置匹配的场景
- 方案2适合拼写检查类场景,仅关注字符存在性及出现次数,不关心位置
- 两个方案均通过循环遍历待比较字符串数组,实现批量对比统计
内容的提问来源于stack exchange,提问作者simon
相关产品推荐
相关产品推荐

