```c #include <stdio.h> // 函数:查找模式串在主串中的位置 int index(char s[], char t[], int pos) { int i = pos, j = 0; // 初始化指示位置 while (s[i]!= '\0' && t[j]!= '\0') { // 当主串和模式串都未结束 if (s[i] == t[j]) { // 若当前字符相等 i++; // 主串位置后移 j++; // 模式串位置后移 if (t[j] == '\0') { // 若模式串结束,匹配成功 return i - j + 1; // 返回匹配开始位置(从 1 计数) } } else { // 若当前字符不相等 i = i - j + 1; // 主串位置回退到本次匹配开始的下一个位置 j = 0; // 模式串位置重置为开头 } } return 0; // 未匹配成功返回 0 } int main() { char s[] = "hello world"; char t[] = "world"; int pos = 0; int result = index(s, t, pos); if (result!= 0) { printf("匹配成功,匹配序号为:%d\n", result); } else { printf("匹配失败\n"); } return 0; } ``` 额外需要注意的逻辑点: 1. 处理边界情况,比如主串或模式串为空的情况。 2. 注意字符数组的结束标志'\0',避免越界访问。 3. 对于匹配成功的判断条件要准确,确保返回的序号是从 1 开始计数的。 [2024-12-15 12:39:10 | AI写代码神器 | 422点数解答]