c中是否有一个函数返回另一个字符串中的字符串索引?

时间:2014-04-23 21:09:30

标签: c string indexing arrays

我有2个char数组

    char page=[4][5] = {{'a','b',' ','d','e'},  {'A',' ','C','D','E'},{'a','b','c','d','e'}, {'A','B','C','D','E'}};
    char word[5]="CDE";

我试图找到单词" CDE"的索引。在page,即7和17。 C中有这个功能吗?或者很短的路。 像,

    int indexlist[]=findindex(word, page);

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

#include <stdio.h>
#include <string.h>

int main(void) {
char page[4][5] = {{'a','b',' ','d','e'},  {'A',' ','C','D','E'},{'a','b','c','d','e'}, {'A','B','C','D','E'}};
    char word[5]="CDE";

// put all the characters in a single long string:
char buf[21];
memcpy(buf, &(page[0][0]), 20);
// and null terminate:
buf[20]='\0';
char *p;
p = buf;
while((p = strstr(p, word))!=NULL) {
  printf("found a match at offset of %d\n", (int)(p - buf));
  p+=strlen(word);
}
}

输出:

found a match at offset of 7
found a match at offset of 17

答案 1 :(得分:0)

标准库中最接近的是strstr

char str1[] = "A CDE";
char str2[] = "CDE";

char *p = strstr( str1, str2 );

p现在指向Cstr1)中的&str1[2]