[关闭]
@rg070836rg 2015-08-16T15:10:44.000000Z 字数 1564 阅读 1540

书上串的基本操作以及BF算法

data_structure


一、简介

一共介绍4个函数,如下:

  1. void StrCat(char * s1,char *s2);
  2. int StrCmp(char* s1,char* s2);
  3. void StrCpy(char* s1,char* s2);
  4. int BFmatching(char* s,char* t);

二、实现

2.1 StrCat

用于连接两个字符串,放到第一位上去

  1. void StrCat(char * s1,char *s2)
  2. {
  3. int len1 = strlen(s1);
  4. int len2 = strlen(s2);
  5. if(len1 + len2 > MaxSize-1)
  6. {
  7. cerr<<"超长";
  8. exi t(1);
  9. }
  10. int i=0;
  11. while (s2[i]!='\0')
  12. {
  13. s1[i+len1] = s2[i];
  14. i++;
  15. }
  16. s1[i+len1] = '\0';
  17. }

要注意,这里由于用到了MAXSIZE判定是否溢出,所以在测试的时候,要把字符串大小置为这么大。

2.2 StrCmp

字符串比较

  • 若s1< s2,输出负数
  • 若s1< s2,输出0
  • 若s1> s2,输出正数

代码如下:

  1. int StrCmp(char* s1,char* s2)
  2. {
  3. int i = 0;
  4. while (s1[i]==s2[i] && s1[i]!='\0')
  5. {
  6. i++;
  7. }
  8. return (s1[i] -s2[i]);
  9. }

2.3 StrCpy

拷贝s2的内容到s1

  1. void StrCpy(char* s1,char* s2)
  2. {
  3. int len = strlen(s2);
  4. if(len > MaxSize-1)
  5. {
  6. cerr<<"超长";
  7. exit(1);
  8. }
  9. while(*s1++= *s2++);
  10. }

2.4 BFmatching

简单的模式匹配算法

  1. int BFmatching(char* s,char* t)
  2. {
  3. int i,j,n,m;
  4. i = 0;
  5. j = 0;
  6. n = strlen(s);
  7. m = strlen(t);
  8. while(i<n && j<m)
  9. {
  10. if(s[i] == t[j])
  11. {
  12. i++;
  13. j++;
  14. }
  15. else
  16. {
  17. i = i - j + 1;
  18. j = 0;
  19. }
  20. }
  21. if(j >= m)
  22. return i-j;
  23. else
  24. return -1;
  25. }

三、测试

  1. int main()
  2. {
  3. char s1[MaxSize] = "Data";
  4. char s2[MaxSize] = " Structures";
  5. cout<<"s1:"<<s1<<endl;
  6. cout<<"s2:"<<s2<<endl;
  7. cout<<"测试连接函数,并输出S1"<<endl;
  8. StrCat(s1,s2);
  9. cout<<s1<<endl;
  10. cout<<endl;
  11. char s3[MaxSize] = "in c++";
  12. char s4[MaxSize] = "c++";
  13. cout<<"测试比较函数(s3,s4),并输出结果"<<endl;
  14. cout<<StrCmp(s3,s4)<<endl;
  15. cout<<endl;
  16. cout<<"测试拷贝函数(s1,s2),并输出结果"<<endl;
  17. StrCpy(s1,s2);
  18. cout<<"拷贝后:"<<endl;
  19. cout<<"s1:"<<s1<<endl;
  20. cout<<"s2:"<<s2<<endl;
  21. cout<<endl;
  22. cout<<"测试BF匹配(s3,s4),并输出结果"<<endl;
  23. int v=BFmatching(s3,s4);
  24. if(v == -1)
  25. {
  26. cout<<"匹配失败"<<endl;
  27. }
  28. else
  29. {
  30. cout<<s4<<"在"<<s3<<"中首次出现的下标为 "<<v<<endl;
  31. }
  32. cout<<endl;
  33. cout<<"测试BF匹配(s4,s3),并输出结果"<<endl;
  34. v=BFmatching(s4,s3);
  35. if(v == -1)
  36. {
  37. cout<<"匹配失败"<<endl;
  38. }
  39. else
  40. {
  41. cout<<s4<<"在"<<s3<<"中首次出现的下标为 "<<v<<endl;
  42. }
  43. return 0;
  44. }

测试截图:
此处输入图片的描述

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注