C中的String.indexOf函数

Rya*_*arn 44 c string

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

到目前为止,我发现的所有功能都像strstr一样会返回找到的char*,而不是它在原始字符串中的位置.

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)

  • 未找到字符时未定义的行为.如果`strchr`就足够了,你也不应该使用`strstr`(有或没有拼写错误). (3认同)
  • 确实,但OP要求的角色不是子串.当然,如果你广泛地解释字符包含多字节字符,`strstr`是正确使用的函数. (2认同)

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)

  • `strcspn`更像是`String.IndexOfAny()` - 搜索`keys`数组中的任何字符.但是,是的,它会成功 (11认同)
  • 上面的注释非常重要 - 在示例中执行它并不模仿indexOf(),因此原始答案非常不正确. (2认同)
  • 这正是您要找的:http://stackoverflow.com/a/1479401/3395760 (2认同)

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