各位高手,看看帮我优化一下我写的程序。给点意见,看看哪里写的不好。

提出问题 解决问题 2006-05-05 11:49:41
我的这个程序的目的是,在字符串中找到子串,并删掉它。这样实现怎么样,我觉得有点可读性比较差,能不能帮我改改。有什么更好的方法没有啊?

#include <stdio.h>

int del_substr(char *str,char const *substr)
{
char const *substr_temp=substr;
char *str_temp=str;
int substr_count=0;
while(*str_temp!='\0')
{
if(*substr_temp==*str_temp)
{
substr_temp++;
substr_count++;
}
else
{
substr_temp=substr;
substr_count=0;
}
str_temp++;
if(*substr_temp=='\0')
{
printf("找到了子串\n");

while(*str_temp!='\0')
{
*(str_temp - substr_count)=*str_temp;
str_temp++;
}
*(str_temp-substr_count)='\0';
return 1;
}
}
return 0;
}

#include <stdio.h>
main()
{
char str[20]="acbcdhcdefg";
char *substr="cde";

printf("原串:%s\n",str);
printf("子串:%s\n",substr);
del_substr(str,substr);
printf("删掉子串之后:%s\n",str);
}
谢谢了。
...全文
183 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuyongwu2008 2006-05-09
  • 打赏
  • 举报
回复
我觉得chenhu_doc衣带渐宽终不悔里的好像有一些不完美,如下:
****
int i=pos;
*****
return i+1;
这样原先pos值为-1,i=pos=-1 则if(res[i+j]==str[j])中的第一个为res[-1]出错!
好像改为
int i=pos+1;
*****
ruturn i;
好一些..学习中****
chenhu_doc 2006-05-07
  • 打赏
  • 举报
回复
废人鄙视csdn的说法 没有多大的理由呀。。。。
chenhu_doc 2006-05-07
  • 打赏
  • 举报
回复
// 虽然主函数写的比较长 但是核心部分还是比较耐看的
chenhu_doc 2006-05-07
  • 打赏
  • 举报
回复
//求子串位置的定位函数index(***,***,int **)

#include <iostream>
#include <string>

using namespace std;

int index(const char *res, const char *str, int pos)
{
/* 若串 S 中从第pos(S 的下标0≤pos<StrLength(S))个字符

起存在和串 T 相同的子串,则称匹配成功,返回第一个

这样的子串在串 S 中的下标,否则返回 -1 */
int i = pos, j = 0;
while ( res[i+j] != '\0'&& str[j] != '\0')

if ( res[i+j] == str[j] )
j ++; // 继续比较后一字符
else
{
i ++; j = 0; // 重新开始新的一轮匹配
}

if ( str[j] == '\0')
return i+1; // 匹配成功 返回下标
else
return -1; // 串S中(第pos个字符起)不存在和串T相同的子串
}


int main()
{
char res[100];
char str[20];

cout<<"input the context to be matched: "<<endl;
cin.getline(res,100,'\n');

cout<<"input the key character:"<<endl;
cin.getline(str,20,'\n');

cout <<res<<endl;
cout <<str<<endl;

int position = -1; //want to specify this variable, use cin....
int index_=position;
int count=0;
do
{
index_ = index(res, str, index_);
if( -1 == index_ )
cout<<"so now,there is no more matching position"<<endl;
else
{
count++;
cout <<"the "<<count<<" matching characters: "<< index_<<endl;
}
}while(index_ != -1);

return 0;
}


//////献丑。。。。
Wolf0403 2006-05-07
  • 打赏
  • 举报
回复
chenhu_doc:偶用 indent 排版的代码缩进啊。。空白全被 CSDN 吃了……
richen_99 2006-05-06
  • 打赏
  • 举报
回复
用KMP算法找子串
Wolf0403 2006-05-06
  • 打赏
  • 举报
回复
http://community.csdn.net/Expert/TopicView3.asp?id=4728782
  • 打赏
  • 举报
回复
kmp算法是什么算法啊?
laiwusheng 2006-05-06
  • 打赏
  • 举报
回复
kmp

69,373

社区成员

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

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