在C语言中,你可以使用`strstr`函数来查找一个字符串在另一个字符串中第一次出现的位置。这个函数在``头文件中定义。如果找到了匹配的子串,`strstr`函数将返回它在主串中的首次出现位置的指针,否则返回NULL。
以下是一个示例代码,定义了一个名为`findSubstring`的函数,用于查找`s1`在`s2`中首次出现的位置,并返回这个位置的索引。
```c
#include
#include
// 查找s1在s2中首次出现的位置
int findSubstring(const char *s1, const char *s2) {
char *result = strstr(s2, s1);
if (result != NULL) {
return result - s2; // 返回索引(s1在s2中的起始位置)
} else {
return -1; // 没有找到,返回-1
}
}
int main() {
const char *s1 = "hello";
const char *s2 = "this is a hello world";
int index = findSubstring(s1, s2);
if (index != -1) {
printf("Substring '%s' found at index %d in string '%s'.\n", s1, index, s2);
} else {
printf("Substring '%s' not found in string '%s'.\n", s1, s2);
}
return 0;
}
```
在这个示例中,`findSubstring`函数使用`strstr`函数查找`s1`在`s2`中首次出现的位置。如果找到,返回索引;如果没有找到,返回-1。然后,在`main`函数中,我们调用`findSubstring`函数,并输出结果。