strstr()函数是标准C语言函数,在linux系统下,运行命令man strstr 可以看到strstr()函数原型为:
$ man strstr
SYNOPSIS
#include
char *strstr(const char *haystack, const char *needle);
DESCRIPTION
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.
函数功能描述: strstr()函数查找needle(第二个参数)在字符串haystack(第一个参数)中首次出现的位置。如果找到,则返回子串首位置的指针值,否则返回NULL。
如果想将指针位置转换成相应的字符偏移位置,可以用返回指针与字符串haystack指针进行相减运算,得到偏移值。参考代码和运行结果如下:
char *p = 0;
char *s1 = "abcd";
char *s2 = "cd";
p=strstr(s1,s2);
int ret = p - s1;
print("%d\n",ret);
p-s1+1就是其位置