|
7.11 本章实例
本节以一个字符串处理程序向读者展示指针的使用。
问题:在一个字符串内容中删除某些字符串。
算法:逐字符比较,若不相等就保留,相等就删除。
【实例7-1】 字符串处理程序代码。 - #include "stdafx.h"
- #include <iostream.h>
- #define _MAX_ 256 //字符串最大长度
- int delstring(char **target,char *source);
- int main()
- {
- char *p_target=0;
- char *p_source=0;
- int k=0;
- p_target=new char[_MAX_];
- p_source=new char[_MAX_];
- cout<<"请输入目标串: ";
- cin>>p_target;
- cout<<"请输入删除串: ";
- cin>>p_source;
- cout<<"在\""<<p_target<<"\"内删除\""<<p_source<<endl;
- cout<<"---------------"<<endl;
- if (strlen(p_target)<strlen(p_source))
- cout<<"目标串长度小于替换串!"<<endl;
- else
- {
- k=delstring(&p_target,p_source);
- if (k>0)
- cout<<p_target<<endl;
- else
- cout<<"没找到!"<<endl;
- }
- delete[] p_target;
- delete[] p_source;
- p_target=0;
- p_source=0;
- return 0;
- }
- int delstring(char **target,char *source)
- {
- char *p_target=*target;
- char *p_source=source;
- char *p_temp=0;
- char *p_next=0;
- int pos=0;
- p_temp=new char[strlen(*target)];
- p_next=p_temp;
- while(strlen(p_target)>=strlen(source))
- {
- if (*p_target==*p_source)
- {
- for(pos=0;pos<strlen(source);pos++)
- {
- if (*(p_target+pos)!=*p_source)
- break;
- p_source++;
- }
-
- if (pos<strlen(source))
- {
- for(int i=0;i<pos;i++)
- {
- *p_next=*(p_target+i);
- p_next++;
- }
- }
- else
- {
- p_target+=pos;
- p_source=source;
- }
- }
- else
- {
- *p_next=*p_target;
- p_next++;
- p_target++;
- }
- }
-
- while(*p_target!='\0')
- {
- *p_next=*p_target;
- p_next++;
- p_target++;
- }
- *p_next='\0';
- delete[] *target;
- *target=p_temp;
- return 1;
- }
分析:代码中的delstring函数负责字符串的删除,该函数分两部分。首先是创建一个临时空间存放处理后的串,然后判断原串中是否有与目标串相等的串。判断时逐个比较,如果全部相等就不需要再转移到临时空间中;如果不相等就需要转移。由于原串可能比目标串要长,所以当比较到后期时,原串中剩余的子串长度可能已经小于目标串,只需直接复制到临时空间中即可。
【责任编辑: 云霞 TEL:(010)68476606】
|