Online Compiler C

#include <stdio.h> #include <string.h> void pack_string(char s[]) { char current = *s; int counter = 0; while (*s != '.') { if (*s == current) { counter++; } else { printf("%c%d", current, counter); counter = 1; } current = *s; s++; } } int main() { char a[] = "zzzzzzzzzzz."; pack_string(a); return 0; }
这段代码试图实现一个字符串压缩功能:将连续重复的字符替换为“字符+重复次数”的形式,遇到句点停止。但输出结果不正确。

- 在循环中,当遇到新字符时,你打印了前一个字符和它的计数,但此时`current`已经被更新为当前字符,而`counter`重置为1,这会导致第一个字符的计数被跳过。例如,对于"zzzzz.",循环开始时`current`是'z',`counter`从0开始,第一次判断`*s == current`成立,`counter`变为1,但之后没有打印,直到遇到新字符或结束。实际上,你需要先处理当前字符的计数,再更新状态。

- 循环结束后,最后一个字符的计数没有被打印。因为循环在遇到'.'时停止,但最后一个字符(句点前的字符)的计数还留在`counter`中,没有输出。