在线编译器 C

#include <stdio.h> #include <string.h> int main() { char s1[1001], s2[1001]; fgets(s1, sizeof(s1), stdin); fgets(s2, sizeof(s2), stdin); int len1 = strlen(s1); int len2 = strlen(s2); if (s1[len1 - 1] == '\n') s1[len1 - 1] = '\0'; if (s2[len2 - 1] == '\n') s2[len2 - 1] = '\0'; int i = 0; while (s1[i] != '\0' && s2[i] != '\0') { if (s1[i] != s2[i]) { printf("%d\n", i); return 0; } i++; } if (s1[i] == '\0' && s2[i] == '\0') { printf("-1\n"); } else { printf("%d\n", i); } return 0; }
This program reads two strings, removes any trailing newline from each, then finds the first position where they differ. If they are identical, it prints -1. Otherwise it prints the index of the first differing character.

- The program currently prints the index of the first difference, but the task likely expects the position of the first character that is different, counting from 1 instead of 0. Check whether the output should be 1-based or 0-based.
- When one string is a prefix of the other, the loop stops because one string ends. The program prints the index `i` at that point, but you should verify if that index correctly represents the first differing position, or if the output should be something else in that case.