在线编译器 C

#include <stdio.h> int counter(char s[]){ int counter = 0; int start = 0, end = 0; int i=0; while(s[i]!='\0'){ if(s[start]==s[end] && start!=end){ counter++; } start = i; while(s[i]!=' '){ end=i; i++; } } return counter; } int main() { char a[1001]; scanf("%[^\n]", a); printf("%d", counter(a)); return 0; }
这段代码试图统计字符串中相邻相同字符对的数量,但逻辑存在明显问题。

代码的主要思路是:遍历字符串,当发现 `s[start] == s[end]` 且 `start != end` 时计数加一。但 `start` 和 `end` 的更新方式不正确,导致无法正确比较相邻字符。

- 内层 `while(s[i]!=' ')` 循环会跳过空格,但遇到空格时循环不会结束,因为条件不满足空格时才会继续,实际上这个循环会一直走到字符串末尾或遇到空格才停,但 `end` 的赋值位置有问题。
- `start` 每次被设为 `i`,但 `i` 在内层循环中已经改变,导致 `start` 和 `end` 的对应关系混乱。
- 代码没有正确比较相邻字符,而是试图用两个指针做某种匹配,但逻辑不清晰。

提示:
- 检查内层循环的条件和 `end` 的赋值时机。你想让 `end` 指向当前字符,但内层循环会跳过空格,这可能导致 `end` 指向了错误的位置。
- 比较相邻字符只需要一个指针,每次比较当前字符和下一个字符即可,不需要两个指针 `start` 和 `end`。