题目描述:
扩展String类,引入头文件CString.h,它的内容如下:
#include <iostream>
using namespace std;
class String{
protected:
char *mystr;
int len;
public:
String(const char *p){
len = strlen(p);
mystr = new char[len+1];
strcpy(mystr,p);
}
~String(){
if (mystr !=NULL)
{
delete []mystr;
mystr = NULL;
len = 0;
}
}
void showStr(){cout <<mystr;}
char * GetStr(){return mystr;}
virtual bool IsSubString(const char *str){
int i,j;
for (i =0;i<len;i++)
{
int k = i;
for (j =0;str[j] !='\0';j++,k++)
{
if (str[j]!= mystr[k]) break;
}
if(str[j] =='\0') return true;
}
return false;
}
};
class EditString:public String{
public:
EditString(const char *p):String(p){}
int IsSubString(int start, const char *str);
void EditChar(char s, char d);
void EditSub(char * subs,char *subd);
void DeleteChar(char ch);
void DeleteSub(char * sub);
};
实现int IsSubString(int start, const char *str);
从start处开始判断str是否为字符串的子串,是则返回子串第一次出现处的下标位置(下标从0开始计算),否则返回-1;
例如:
EditString es("testtesttest");
es.IsSubString(3,"test");//4
实现EditChar(char s, char d),用字符d代替所有字符s,例如:
EditString es("testtesttest");
es.EditChar('t','a');//"aesaaesaaesa"
实现void EditSub(char * subs,char *subd),用字符串subd代替所有字符串subs,例如:
EditString es("testtesttest");
es.EditChar(“test”,“str”);//"strstrstr"
实现void DeleteChar(char ch),将所有ch字符删除,例如:
EditString es("testtesttest");
es.DeleteChar('t');//"eseses"
实现void DeleteSub(char * sub),将所有的字符串sub删除,例如:
EditString es("testtesttest");
es.DeleteSub(”es“);//"tttttt";
实现:
#include"CString.h"
int EditString::IsSubString(int start, const char* str)
{
int i, j;
for (i = 0; i < len; i++)
{
int k = start+i;
for (j = 0; str[j] != '\0'; j++, k++)
{
if (str[j] != mystr[k]) break;
}
if (str[j] == '\0') return start + i;
}
return -1;
}
void EditString::EditChar(char s, char d)
{
int i = 0;
while (mystr[i])
{
if (mystr[i] == s)
mystr[i] = d;
i++;
}
}
void EditString::EditSub(const char* subs,const char* subd)//提交时去掉const
{
int i, j,len_s=strlen(subs),len_d=strlen(subd);
for (i = 0; i < len; i++)
{
int k = i;
for (j = 0; subs[j] != '\0'; j++, k++)
{
if (subs[j] != mystr[k]) break;
}
if (subs[j] == '\0')
{
int m = i + len_s;
while (mystr[m-1])//注意
{
mystr[m + len_d - len_s] =mystr[m];
m++;
}
m = 0;
while (subd[m])
{
mystr[i + m] = subd[m];
m++;
}
i += (len_d-1);
}
}
}
void EditString::DeleteChar(char ch)
{
int i=0;
while (mystr[i])
{
while (mystr[i] == ch)
{
int j = i;
while (mystr[j])
{
mystr[j] = mystr[j + 1];
j++;
}
}
i++;
}
}
void EditString::DeleteSub(const char* sub)//提交时去掉const
{
int i, j;
for (i = 0; i < len; i++)
{
int k = i;
for (j = 0; sub[j] != '\0'; j++, k++)
{
if (sub[j] != mystr[k]) break;
}
if (sub[j] == '\0')
{
int len = strlen(sub);
int m = i+len;
while (mystr[m-1])
{
mystr[m - len] = mystr[m];
m++;
}
}
}
}