C语言 如何在C中的char数组中搜索字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13450809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:28:47 来源:igfitidea点击:
How to search a string in a char array in C?
提问by hassasin
For example I have:
例如我有:
char buff[1000];
I want to search if the string "hassasin" is in that char array. Here is what I have tried.
我想搜索字符串“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"
}
}
采纳答案by phschoen
if the chararray contains stringend or do not end with \0 you can use these code, because strstr will brake on these ones:
如果 chararray 包含 stringend 或不以 \0 结尾,您可以使用这些代码,因为 strstr 会在这些代码上刹车:
#include <stdio.h>
int main()
{
char c_to_search[5] = "asdf";
char text[68] = "hello my name is #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
}
there is some other string behind it \n##代码## 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;
}

