【问题标题】:How to search a string in a char array in C? [closed]如何在C中的char数组中搜索字符串? [关闭]
【发布时间】:2012-11-19 09:23:55
【问题描述】:

例如我有:

char buff[1000];

我想搜索字符串“hassasin”是否在该字符数组中。这是我尝试过的。

char word[8] = "hassasin";
char Buffer[1000]=sdfhksfhkasd/./.fjka(hassasin)hdkjfakjsdfhkksjdfhkjh....etc 
int k=0;
int t=0; 
int len=0; 
int sor=0; 
for (k=0; k<1000; k++){ 
    for (t=0; t<8; t++){ 
        if (Buffer[k]==word[t]) len++; 
        if (len==8) "it founds 0.9.1" 
    } 
}

【问题讨论】:

  • 您应该尝试编写自己的代码,然后询问您是否成功。
  • 我试过了,但我找不到真正的答案
  • 我不知道有多少次遇到“已关闭...这个问题不太可能帮助任何未来的访客”,并且答案非常有帮助。

标签: c arrays string


【解决方案1】:

是的,您可以为此使用strstr

 #include <stdlib.h>
 #include <string.h>

 char buff[1000];
 char *s;

 s = strstr(buff, "hassasin");      // search for string "hassasin" in buff
 if (s != NULL)                     // if successful then s now points at "hassasin"
 {
     printf("Found string at index = %d\n", s - buff);
 }                                  // index of "hassasin" in buff can be found by pointer subtraction
 else
 {
     printf("String not found\n");  // `strstr` returns NULL if search string not found
 }

【讨论】:

  • 谢谢。有没有办法手动完成?不使用任何方法?
  • 当然可以——如果这是为了家庭作业,你可以自己实现strstr——这是一个非常简单的函数,在编写它的过程中你会学到很多东西。跨度>
【解决方案2】:

如果 chararray 包含 stringend 或不以 \0 结尾,您可以使用这些代码,因为 strstr 会阻止这些代码:

#include <stdio.h>
int main()
{
    char c_to_search[5] = "asdf";

    char text[68] = "hello my name is \0 there is some other string behind it \n\0 asdf";

    int pos_search = 0;
    int pos_text = 0;
    int len_search = 4;
    int len_text = 67;
    for (pos_text = 0; pos_text < len_text - len_search;++pos_text)
    {
        if(text[pos_text] == c_to_search[pos_search])
        {
            ++pos_search;
            if(pos_search == len_search)
            {
                // match
                printf("match from %d to %d\n",pos_text-len_search,pos_text);
                return;
            }
        }
        else
        {
           pos_text -=pos_search;
           pos_search = 0;
        }
    }
    // no match
    printf("no match\n");
   return 0;
}

http://ideone.com/2In3mr

【讨论】:

  • 好的,但我认为即使在必要的字母之间还有其他元素,这段代码也能找到字符串。在我的搜索中,我想找到确切的单词,它们之间没有其他字母。我该怎么做?
  • 此代码搜索完全相同的单词。如果你想用空格搜索它,你可以搜索“asdf”
  • 每次找到匹配的字母时我都没有得到它,它正在执行 ++pos_search。它不必是连续的,当它达到 4 时,它说我找到了。
  • 不,它必须是连续的,因为如果没有与 'pos_text -=pos_search; 匹配的字母,位置会重置pos_search = 0;'
  • 我现在知道了,代码很棒,谢谢
猜你喜欢
  • 1970-01-01
  • 2018-12-15
  • 2014-03-26
  • 2015-06-17
  • 2018-06-23
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多