BUPT-homework/semester1/pset13/1-4-LocateSubStr.c
2021-12-10 21:22:20 +08:00

42 lines
874 B
C

#include <stdio.h>
char *locatesubstr(char *str1, char *str2);
int main() {
char str1[505], str2[505];
char *p;
// Was gets in the example, but it is unsafe.
fgets(str1, 505, stdin);
fgets(str2, 505, stdin);
p = locatesubstr(str1, str2);
if (p == NULL)
printf("NULL!\n");
else
puts(p);
return 0;
}
/* 请在这里填写答案 */
char *locatesubstr(char *str1, char *str2) {
char *loc = NULL;
int i;
while (*str1 != '\0' && loc == NULL) {
if (*str1 == *str2) { // Head matched
loc = str1;
i = 1;
while (*(str2 + i) != '\0') {
if (*(str1 + i) != *(str2 + i) &&
*(str2 + i) != '\n' && // Because gets also inputs the \n
*(str1 + i) != '\n') { // So we need to take care of that.
loc = NULL;
break;
}
i++;
}
}
str1++;
}
return loc;
}