要用c++编一个简单的txt匹配搜索的小软件,求如何解决,,,

vince4321 2014-03-13 06:08:15
要用c++编一个简单的txt匹配搜索的小软件,求如何解决,,,
...全文
96 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
引用 3 楼 zhao4zhong1 的回复:
直接将linux源代码中grep的源代码拿来用。
简单点的可以参考:
//摘自《代码之美》
// 字符     含义
// .        匹配任意的单个字符
// ^        匹配输入字符串的开头
// $        匹配输入字符串的结尾
// *        匹配前一个字符的零个或者多个出现
#include <stdio.h>
int matchhere(char *regexp, char *text);

int matchstar(int c, char *regexp, char *text) {// matchstar: search for c*regexp at beginning of text
   do {// a * matches zero or more instances
       if (matchhere(regexp, text)) return 1;
   } while (*text != '\0' && (*text++ == c || c == '.'));
   return 0;
}
int matchhere(char *regexp, char *text) {// matchhere: search for regexp at beginning of text
   if (regexp[0] == '\0') return 1;
   if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text);
   if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0';
   if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1);
   return 0;
}

int match(char *regexp, char *text) {// match: search for regexp anywhere in text
    if (regexp[0] == '^') return matchhere(regexp+1, text);
    do {// must look even if string is empty
        if (matchhere(regexp, text)) return 1;
    } while (*text++ != '\0');
    return 0;
}
void main() {
    printf("%d==match(abc ,abc)\n",match("abc" ,"abc"));
    printf("%d==match(^a  ,abc)\n",match("^a"  ,"abc"));
    printf("%d==match(c$  ,abc)\n",match("c$"  ,"abc"));
    printf("%d==match(a.c ,abc)\n",match("a.c" ,"abc"));
    printf("%d==match(a.*c,abc)\n",match("a.*c","abc"));
    printf("-------------------\n");
    printf("%d==match(ABC ,abc)\n",match("ABC" ,"abc"));
    printf("%d==match(^B  ,abc)\n",match("^B"  ,"abc"));
    printf("%d==match(A$  ,abc)\n",match("A$"  ,"abc"));
    printf("%d==match(a..c,abc)\n",match("a..c","abc"));
    printf("%d==match(a.*d,abc)\n",match("a.*d","abc"));
}
//1==match(abc ,abc)
//1==match(^a  ,abc)
//1==match(c$  ,abc)
//1==match(a.c ,abc)
//1==match(a.*c,abc)
//-------------------
//0==match(ABC ,abc)
//0==match(^B  ,abc)
//0==match(A$  ,abc)
//0==match(a..c,abc)
//0==match(a.*d,abc)
ultimater 2014-03-14
  • 打赏
  • 举报
回复
用C++里stream和string吧,很好解决的。PS:我原来做过带正则表达示的工具。
赵4老师 2014-03-14
  • 打赏
  • 举报
回复
直接将linux源代码中grep的源代码拿来用。
gz_qmc 2014-03-14
  • 打赏
  • 举报
回复
用C多简单,搞么C++
Walle_Oyq 2014-03-14
  • 打赏
  • 举报
回复
1. 要是简单的小程序的话,使用 strstr()这个函数去匹配,这个函数很强大的。 2. 如果是想做的正规一点,有实际用途的话,推荐楼主使用正则表达式来匹配。 3. 如果是想学习算法的话,推荐楼主使用 KMP算法。
Sniper_Pan 2014-03-14
  • 打赏
  • 举报
回复
string 用自带的find基本搞定

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧