如何在搜索用C字符数组的字符串? [英] How to search a string in a char array in C?

查看:136
本文介绍了如何在搜索用C字符数组的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有:

 字符的buff [1000];

我想如果搜索字符串hassasin是该字符数组。这里是什么我都试过了。

 字符字[8] =hassasin;
字符缓冲区[1000] = sdfhksfhkasd /./。fjka(hassasin)hdkjfakjsdfhkksjdfhkjh ....等
INT K = 0;
INT T = 0;
INT LEN = 0;
INT SOR = 0;
对于(K = 0; K< 1000; k ++){
    对于(t = 0; T< 8;吨++){
        如果(缓冲[K] ==字[T])LEN ++;
        如果(LEN == 8),它开创0.9.1
    }
}


解决方案

如果chararray包含stringend或者不以\\ 0结束了,你可以使用这些code,因为的strstr都会对这些的刹车:

 的#include<&stdio.h中GT;
诠释的main()
{
    炭c_to_search [5] =ASDF;    字符文本[68] =你好,我的名字是\\ 0有它背后\\ n \\ 0 ASDF其他一些字符串;    INT pos_search = 0;
    INT pos_text = 0;
    INT len_search = 4;
    INT len_text = 67;
    为(pos_text = 0; pos_text&下; len_text - len_search ++ pos_text)
    {
        如果(文[pos_text] ==​​ c_to_search [pos_search])
        {
            ++ pos_search;
            如果(pos_search == len_search)
            {
                // 匹配
                的printf(从%d个匹配%d个\\ N,pos_text-len_search,pos_text);
                返回;
            }
        }
        其他
        {
           pos_text - = pos_search;
           pos_search = 0;
        }
    }
    //不匹配
    的printf(无匹配\\ n);
   返回0;
}

http://ideone.com/2In3mr

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.

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

解决方案

if the chararray contains stringend or do not end with \0 you can use these code, because strstr will brake on these ones:

#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

这篇关于如何在搜索用C字符数组的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆