在线编译器 C

#include <stdio.h> #include <string.h> void pack_string(char s[]) { int counter = 1; int i = 0; int current = s[0]; while (s[i] != '.') { if (s[i + 1] == current) { counter++; i++; } else if (s[i + 1] != current || s[i + 1] == '.') { putchar(current); printf("%d", counter); counter = 1; current = s[i + 1]; i++; } } return; } int main() { char a[] = "aaaaabbbc."; pack_string(a); return 0; }
这段代码试图实现一个字符串压缩功能:将连续重复的字符替换为“字符+重复次数”的形式。例如 "aaaaabbbc." 应该输出 "a5b3c1"。

代码中存在逻辑错误,导致输出结果不正确。

- 在循环中,当遇到新字符时,`current` 被更新为 `s[i+1]`,但此时 `i` 已经自增,导致下一次循环比较时可能跳过字符或访问越界。需要仔细检查索引更新的顺序和条件判断的逻辑。
- 循环结束后,最后一个字符的计数没有被输出。因为循环在遇到 '.' 时退出,但最后一个字符组(如 'c')的计数尚未打印。