【问题标题】:Is there a function in c that returns the index of a string in another string?c中是否有一个函数可以返回另一个字符串中字符串的索引?
【发布时间】:2014-04-23 21:09:29
【问题描述】:

我有 2 个字符数组

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

我试图在page 中找到单词“CDE”的索引,即 7 和 17。 C中有一个函数吗?或短途。 有点像,

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

【问题讨论】:

  • 你看过strstr吗?它必须在您的页面上“一次一行”运行。
  • 您可以零终止page,然后使用strstr 获取地址。
  • strstr 或 safe(r) strnstr

标签: c string indexing arrays


【解决方案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

【讨论】:

  • 是的,我认为复制到buf 是更好的选择。
  • @Floris 就像一个魅力!谢谢!
  • @user3551975:欢迎来到 Stackoverflow!作为新用户,您可能对游览感兴趣:About Stackoverflow。 “谢谢”表示赞赏,但通常的程序是表明答案是有用的接受:Someone answered my question, what now?
【解决方案2】:

标准库中最接近的东西是strstr:

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

char *p = strstr( str1, str2 );

p 现在指向str1 (&amp;str1[2]) 中的C

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2023-03-05
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多