C语言中的String.indexOf函数

时间:2020-03-05 18:38:21  来源:igfitidea点击:

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

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

解决方案

回答

如果我们不完全依赖纯C并可以使用string.h,则可以使用strchr()
看这里

回答

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" */
}

回答

编辑:strchr仅对一个字符更好。
指针式算术说" Hellow!":

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

重要提示:如果未找到任何字符串,strchr()将返回NULL

回答

我们可以使用strstr完成所需的操作。例子:

char *a = "Hello World!";
char *b = strstr(a, "World");

int position = b - a;

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

产生结果:

the offset is 6

回答

我觉得

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;
}