在线编译器 C

#include <stdio.h> int main() { char str[1001]; fgets(str, sizeof(str), stdin); int count = 0; int i = 0; while (str[i] != '\0') { while (str[i] == ' ') { i++; } if (str[i] == '\0') { break; } char first = str[i]; if (first >= 'A' && first <= 'Z') { first = first - 'A' + 'a'; } while (str[i] != ' ' && str[i] != '\0') { i++; } if (i > 0 && str[i-1] != ' ') { char last = str[i-1]; if (last >= 'A' && last <= 'Z') { last = last - 'A' + 'a'; } if (first == last) { count++; } } } printf("%d", count); return 0; }
This program reads a line of text and counts how many words have the same first and last letter (case-insensitive). It skips spaces, processes each word, and compares the lowercase versions of the first and last characters.

- The inner `while (str[i] == ' ')` loop skips spaces, but after this loop, if the string ends, the code breaks. However, consider what happens when there are multiple spaces between words — the outer loop continues correctly, but the logic for detecting the last character of a word may be affected if the word ends right before a space or null terminator.
- The condition `if (i > 0 && str[i-1] != ' ')` is used to get the last character, but after the inner word loop, `i` points to a space or null. This works, but think about whether the last character is always correctly identified when the word is at the very end of the string.