查找字符串简单实现

  一直对编辑器里字符串查找功能感觉很神奇,今天脑子转了一转,用自己的想法简单实现了。

我受数字电路课里画状态图的习题的启发,比如一个字符串“hello”,设置一个状态变量state为0,没有查找到h时state为0,查到h时变为1,查到e时变为2.....其中有任何不匹配的state变为0,当state为"hello"长度5时,则查到了这个数

 

下面贴C代码:

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

int main(){
   
   char word[] = "hello";   //所需查找的字符串
   short wordlen = strlen(word);
   short state = 0;           //匹配状态
   //以第0行和第0列为起始点 
   int row = 0; 
   int col = 0;
   int word_row = 0;  //目标字符所在位置
   int word_col = 0;        //
   
   FILE *pt_file = fopen("D:\\testfile.txt","r"); 
   char temp_c;
   while( !feof(pt_file) ){
        temp_c = fgetc(pt_file);//读取一个字符
        
        if( 0 == state ){
           //这里有可能是所要单词的起始位置 
           word_row = row;
           word_col = col;    
        }
        
        //匹配字符 
        if( word[state] == temp_c ){
             state++;
             //printf("i find:%c\n",temp_c);
        }else{
             state = 0;      
        }
            
        //行列计数,如遇换行符则新的一行开始 
        col++;
        if( temp_c == '\n'){
            row++;    
            col = 0;
        }    
        
        //状态变量到顶,即查到了所要的字符串       
        if( state == wordlen){
           printf("I find it in row:%d  col:%d\n",word_row,word_col);    
        }                 
   } 
   system("PAUSE");
   return 0;   
}

 

//当然实际中不能这个简单,磁盘读取是很慢的,应该要开辟一块缓存,一边从磁盘读取一边查找,不过这就要很多代码了

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值