Bil*_*ill 34
strstr 返回一个指向找到的字符的指针,所以你可以使用指针算法:(注意:这段代码没有测试它的编译能力,它离伪代码只有一步之遥.)
char * source = "test string"; /* assume source address is */
/* 0x10 for example */
char * found = strstr( source, "in" ); /* should return 0x18 */
if (found != NULL) /* strstr returns NULL if item not found */
{
int index = found - source; /* index is 8 */
/* source[8] gets you "i" */
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*rks 15
我觉得
size_t strcspn(const char*str1,const char*str2);
是你想要的.这是从这里拉出的一个例子:
/* strcspn example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "fcba73";
char keys[] = "1234567890";
int i;
i = strcspn (str,keys);
printf ("The first number in str is at position %d.\n",i+1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*der 12
编辑:strchr只对一个char更好.指针aritmetics说"Hellow!":
char *pos = strchr (myString, '#');
int pos = pos ? pos - myString : -1;
Run Code Online (Sandbox Code Playgroud)
重要说明:如果未找到任何字符串,strchr()将返回NULL