C中的String.indexOf函数

C中的String.indexOf函数

String.indexOf function in C

是否有一个 C 库函数可以返回字符串中字符的索引?

到目前为止,我发现的只是 strstr 之类的函数,它们将返回找到的字符 *,而不是它在原始字符串中的位置。


strstr 返回一个指向找到的字符的指针,因此您可以使用指针算法:(注意:此代码未测试其编译能力,它距离伪代码仅一步之遥。)

1
2
3
4
5
6
7
8
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" */
}

我认为

size_t strcspn ( const char * str1, const char * str2 );

是你想要的。这是从此处提取的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 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.\
"
,i+1);
  return 0;
}

编辑:strchr 仅适用于一个字符。
指针算法说"Hellow!":

1
2
char *pos = strchr (myString, '#');
int pos = pos ? pos - myString : -1;

重要提示:如果没有找到字符串,strchr() 返回 NULL


你可以使用 strstr 来完成你想要的。示例:

1
2
3
4
5
6
7
char *a ="Hello World!";
char *b = strstr(a,"World");

int position = b - a;

printf("the offset is %i\
"
, position);

这会产生结果:

1
the offset is 6

你可以写

1
2
s="bvbrburbhlkvp";
int index=strstr(&s,"h")-&s;

在给定的乱码中查找'h'的索引。


写你自己的:)

来自 BSD 许可的 C 字符串处理库的代码,称为 zString

https://github.com/fnoyanisi/zString

1
2
3
4
5
6
7
8
9
10
int zstring_search_chr(char *token,char s){
    if (!token || s=='\\0')
        return 0;

    for (;*token; token++)
        if (*token == s)
            return 1;

    return 0;
}

如果你不完全依赖纯 C 并且可以使用 string.h,那么 strchr()
看这里


推荐阅读