分享字符串查找函数 求指导

Joseph_1118 2012-10-13 06:55:49
char* find(char* data_buf, char* pattern)
{
char* buf_cur = data_buf;
char* pt_cur = pattern;

char* last_find_str = NULL;
int last_find = 0;

if (NULL == data_buf
|| NULL == pattern)
{
return NULL;
}

while (*buf_cur != 0 && *pt_cur != 0)
{
if (*buf_cur == *pt_cur)
{
if (0 == last_find)
{
last_find_str = buf_cur;
}

buf_cur++;
pt_cur++;

last_find = 1;
}
else
{
if (last_find)
{
buf_cur = last_find_str + 1;
pt_cur = pattern;
}
else
{
buf_cur++;
}

last_find = 0;
}
}

if (0 == *pt_cur)
{
return last_find_str;
}

return NULL;
}
...全文
96 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Joseph_1118 2012-10-13
  • 打赏
  • 举报
回复
我老婆写的字符串查找函数竟然和strstr一样...
我写的是用了一层循环的,用自动机推出来的。
[Quote=引用 5 楼 的回复:]

C/C++ code
char * __cdecl cc_strstr(
const char *str1,
const char *str2
)
{
char *str1Cp = (char *)str1;
char *s1, *s2;

if(!*str2)
re……
[/Quote]
hongwenjun 2012-10-13
  • 打赏
  • 举报
回复
char * __cdecl cc_strstr(
const char *str1,
const char *str2
)
{
char *str1Cp = (char *)str1;
char *s1, *s2;

if(!*str2)
return (char *)str1;

while(*str1Cp)
{
s1 = str1Cp;
s2 = (char *)str2;
while(*s1 && *s2 && !(*s1 - *s2))
++s1, ++s2;

if(!*s2)
return str1Cp;

++str1Cp;
}
return NULL;
}

请看别人写的 strstr
http://code.google.com/p/windows-libc/source/browse/trunk/libc_cc/src/cc_string.c
hongwenjun 2012-10-13
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <string.h>

char* find(char* data_buf, char* pattern);
int main()
{
char s[] = " char* find(char* data_buf, char* pattern)";
printf("%s\n", find(s , "find"));
printf("%s\n", strstr(s , "find"));
return 0;
}

// char *strstr( const char *str1, const char *str2 );
// 功能:函数返回一个指针,它指向字符串str2 首次出现于
// 字符串str1中的位置,如果没有找到,返回NULL。

char* find(char* data_buf, char* pattern)
{
char* buf_cur = data_buf;
char* pt_cur = pattern;
char* last_find_str = NULL;
int last_find = 0;
if (NULL == data_buf
|| NULL == pattern) {
return NULL;
}

while (*buf_cur != 0 && *pt_cur != 0) {
if (*buf_cur == *pt_cur) {
if (0 == last_find) {
last_find_str = buf_cur;
}

buf_cur++;
pt_cur++;
last_find = 1;
} else {
if (last_find) {
buf_cur = last_find_str + 1;
pt_cur = pattern;
} else {
buf_cur++;
}

last_find = 0;
}
}

if (0 == *pt_cur) {
return last_find_str;
}

return NULL;
}


楼主代码好像是 strstr函数
AnYidan 2012-10-13
  • 打赏
  • 举报
回复
指导什么?
qing372829210 2012-10-13
  • 打赏
  • 举报
回复
能写点注释吗!!
Joseph_1118 2012-10-13
  • 打赏
  • 举报
回复
我操 CSDN这帖子里面代码怎么设置 怎么这么丑

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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