[英]String.indexOf function in C
是否有一个C库函数将返回字符串中字符的索引?
到目前为止,我发现的所有功能都像strstr一样会返回找到的char *,而不是它在原始字符串中的位置。
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" */
}
我觉得
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;
}
编辑:strchr只对一个char更好。 指针aritmetics说“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
写你自己的:)
用于C的BSD许可字符串处理库的代码,称为zString
https://github.com/fnoyanisi/zString
int zstring_search_chr(char *token,char s){
if (!token || s=='\0')
return 0;
for (;*token; token++)
if (*token == s)
return 1;
return 0;
}
你可以写
s="bvbrburbhlkvp";
int index=strstr(&s,"h")-&s;
在给定的乱码中找到'h'
的索引。
如果你没有完全依赖于纯C并且可以使用string.h,那么有strchr() 请看这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.