搜索字符串的三种方法

来源:互联网 发布:长款流苏耳环淘宝价 编辑:程序博客网 时间:2024/06/05 08:31
[cpp] FILE *fp=_tfopen(szXmlFilePath,L"rb");  
  1. if (fp==NULL)  
  2.     return;  
  3.   
  4. fseek(fp,0,SEEK_END);  
  5. UINT nLen=ftell(fp);    
  6. fseek(fp,0,SEEK_SET);  
  7. // 宽字符类型     
  8. wchar_t* pStr_Read = new wchar_t[nLen/2+1];      //   分配空间    
  9. memset(pStr_Read,0,sizeof(wchar_t)*(nLen/2+1));  //   清空    
  10. fread(pStr_Read,1,nLen,fp);  
  11. fclose(fp);  

    pStr_Read保存的是字符串,要在这个字符串中判断 是否包含子字符串subStr



方法一:转换为CSting 使用CString::Find()

[cpp] CString subStr=L"你好";  
  1.   
  2. CString xmlData=pStr_Read;  
  3. delete []pStr_Read;  // 释放空间    
  4.   
  5. if (xmlData.Find(subStr)!=-1)  
  6. {  
  7.     //...   
  8. }  


方法二:使用字符串搜索函数_tcsstr()

[cpp] view plaincopyprint?
  1. CString subStr=L"你好";  
  2. if (_tcsstr(pStr_Read,subStr))  
  3. {  
  4.     //...   
  5. }  


方法三: 使用KMP匹配算法


[cpp] view plaincopyprint?
  1. int next[20] ={0};  
  2.   
  3. void Next(wchar_t* p,int *next)  
  4. {  
  5.     int len=_tcslen(p);  
  6.   
  7.     int j,k;  
  8.     next[0]=-1;  
  9.     j=0;  
  10.     k=-1;  
  11.     while(j<len-1)  
  12.     {  
  13.         if(k==-1||p[j]==p[k])    //匹配的情况下,p[j]==p[k]  
  14.         {  
  15.             j++;  
  16.             k++;  
  17.             next[j]=k;  
  18.         }  
  19.         else                   //p[j]!=p[k]  
  20.             k=next[k];  
  21.     }  
  22.   
  23. }  
  24.   
  25. //des是目标串,pat是模式串,len1和len2是串的长度  
  26. int kmp(wchar_t des[],int len1,wchar_t pat[],int len2)  
  27. {  
  28.   
  29.     int p=0,s=0;  
  30.     while(p < len2  && s < len1)  
  31.     {  
  32.         if(pat[p] == des[s])  
  33.         {  
  34.             p++;s++;  
  35.         }  
  36.         else  
  37.         {  
  38.             if(p==0)   
  39.             {  
  40.                 s++;//若第一个字符就匹配失败,则从des的下一个字符开始  
  41.             }  
  42.             else  
  43.             {  
  44.                 p = next[p];//用失败函数确定pat应回溯到的字符  
  45.             }  
  46.         }  
  47.     }  
  48.     if(p < len2)//整个过程匹配失败  
  49.     {  
  50.         return -1;  
  51.     }  
  52.     return s-len2;  
  53. }  

 

 


 

[cpp] CString subStr=L"你好";  
  1. if (kmp(pStr_Read,nLen/2,subStr,subStr.GetLength()))  
  2. {  
  3.     //...   
  4. }  
0 0