本题使用strstr()和strcspn函数可实现快速解答。
#include <stdio.h>
#include <string.h>
int main() {
char mainStr[20];
char subStr[20];
fgets(mainStr, 20, stdin);
fgets(subStr, 20, stdin);
mainStr[strcspn(mainStr, "\n")] = '\0';//删除换行符
subStr[strcspn(subStr, "\n")] = '\0';
char * position = strstr(mainStr, subStr);//使用strstr函数快速查找
if (position != NULL) {
printf("%ld\n", position - mainStr + 1);
} else {
printf("No!\n");
}
return 0;
}
cspn函数用法:
在C语言中,strcspn
函数用于查找字符串中第一个不包含在指定字符集合中的字符的位置。该函数的原型如下:
size_t strcspn(const char *str1, const char *str2);
其中,str1
是要进行搜索的字符串,str2
是包含要搜索的字符集的字符串。
strcspn
函数会返回字符串 str1
开头连续不包含在字符串 str2
中的字符个数。换句话说,它返回两个字符串中第一次出现匹配的位置。
例如,下面的代码演示了strcspn函数的用法:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char set[] = "aeiou";
size_t position = strcspn(str, set);
printf("The first character not in the set is at position %zu\n", position);
return 0;
}
Hello中的‘e'首次出现了字符集合’aeiou'中的一个(任意的),因此输出结果position为1(e的下标是1).
strstr函数用法:
在C语言中,strstr
函数用于在一个字符串中查找指定子字符串的位置。其函数原型如下:
char *strstr(const char *haystack, const char *needle);
其中,haystack
是要搜索的字符串,needle
是要查找的子字符串。
strstr
函数会返回一个指向第一次出现子字符串的位置的指针。如果没有找到子字符串,它将返回NULL。
这道题不用关注strstr返回的具体值,只需判断strstr是否返回空指针即可。