c语言中position函数的作用,C语言中的String.indexOf函数

C语言中的String.indexOf函数

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

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

Ryan Ahearn asked 2020-07-19T14:49:55Z

7个解决方案

34 votes

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

}

Bill answered 2020-07-19T14:50:51Z

15 votes

我觉得

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

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

/* strcspn example */

#include

#include

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;

}

Jonathan Works answered 2020-07-19T14:50:27Z

11 votes

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

char *pos = strchr (myString, '#');

int pos = pos ? pos - myString : -1;

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

Michal Sznajder answered 2020-07-19T14:51:17Z

3 votes

您可以使用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

Kyle Cronin answered 2020-07-19T14:51:43Z

0 votes

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

Adam Haile answered 2020-07-19T14:52:02Z

0 votes

写你自己的:)

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

[HTTPS://GitHub.com/发难哦亚尼斯/在string]

int zstring_search_chr(char *token,char s){

if (!token || s=='\0')

return 0;

for (;*token; token++)

if (*token == s)

return 1;

return 0;

}

fnisi answered 2020-07-19T14:52:31Z

0 votes

你可以写

s="bvbrburbhlkvp";

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

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

snack0verflow answered 2020-07-19T14:52:56Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值