您的位置:首页 > 编程语言 > C语言/C++

【c++类与对象练习】判断字符串str是否为当前串的子串

2015-06-05 19:45 471 查看
</pre>   <span style="font-size:24px">定义一个字符串类String,增加下列成员函数:</span><p></p><p><span style="font-size:18px"></span></p><pre name="code" class="cpp">//(a)bool IsSubString (const char * str);判断str是否为当前串的子串;
//(b)bool IsSubString (const String &Str);判断str是否为当前串的子串;


class String
{
private:
char *Str;
int Len;
public:
String(char *Str)
{
this->Len=strlen(Str);
this->Str=new char[this->Len+1];
strcpy(this->Str,Str);
}
bool IsSubString(const char *str);
bool IsSubString(const String &Str1);
int str2num();
void toUppercase();
~String()
{
if(Str!=NULL)
{
delete []Str;
Str=NULL;
}
}
};

bool String::IsSubString(const char *str)
{
int i,j;
int len=strlen(str);
for(i=0;i<Len;i++)
{
if(Str[i]==str[0])//遍历母串,在母串中寻找待定串的首字符
{
int n=0;
for(j=0;j<len;j++)
{
if(Str[i+j]!=str[j])//对比首字符后面字符是否依次相同,并记下相同的个数
break;     //一旦有不同的字符出现,跳出循环
else
n++;
}
if(n==len) //若母串中连续与待定串相同字符的个数等于待定串串的长度,即可认定此字符串为子串
return true;
}

}
}

bool String::IsSubString(const String &Str1)
{
char *str=Str1.Str;
int len=Str1.Len;
int i,j;
for(i=0;i<Len;i++)
{
if(Str[i]==str[0])
{
int n=0;
for(j=0;j<len;j++)
{
if(Str[i+j]!=str[j])
break;
else
n++;
}
if(n==len)
return true;
}

}

}

int main()
{
String Str1("abxxbcdf");
if(Str1.IsSubString("cdf")==true)
{cout<<"是子字符串"<<endl;}
else
{cout<<"不是子字符串"<<endl;}
String Str2("bxx");
if(Str1.IsSubString(Str2)==true)
{cout<<"是子字符串"<<endl;}
else
{cout<<"不是子字符串"<<endl;}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ string 子串