从前往后查找子字符串的c语言函数
时间: 2024-10-12 13:09:54 浏览: 48
在 C 语言中,如果你想要从前往后查找子字符串,可以使用标准库函数 strstr()
。这个函数原型通常定义在 <string.h>
头文件中,它的作用是在给定的主字符串(也称为"haystack")中查找指定的子字符串("needle"),并返回第一次找到子字符串的位置指针。
strstr(haystack, needle)
的工作原理是:
- 检查
haystack
是否以needle
开始。如果是,它会返回haystack
的地址。 - 如果不是,它会在
haystack
的剩余部分继续搜索needle
。 - 如果在整个字符串中都没有找到
needle
,则返回 NULL 表示未找到。
这是一个基本的例子:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char substr[] = "World";
char* result = strstr(str, substr);
if (result) {
printf("Substring found at position %ld\n", (long) result - (long) str); // 注意这里减去str的地址得到偏移量
} else {
printf("Substring not found.\n");
}
return 0;
}
相关推荐


















