判断字符串s2能否经过s1循环移位得到 (二)

2014-11-23 23:18:24 · 作者: · 浏览: 11
c,des))
cout<<"OK"<
else
cout<<"NO"<
strcpy(src, "abcdef"),strcpy(des,"bc");
if(IsSubstring(src,des))
cout<<"OK"<
else
cout<<"NO"<
}
/*
NO
OK
总结:
1,char *strstr( const char *string, const char *strCharSet );
char str[] = "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char* pdest = strstr( string, str );则pdest = lazy fox;
2,关于strcat,MSDN上有一段话No overflow checking is performed when strings are copied or appended.
The behavior of strcat is undefined if the source and destination strings overlap.也就是说源串和目的串不能重叠,否则出错。所以strcat(s,s)是未定义的
*/<2>自定义strcat之MyStrcat,解密src与des内存不能重叠原因。
[cpp] #include
#include
#include
using namespace std;
////////////////////////////////////
char* MyStrcat(char* src,char* des)
{
assert(src!=NULL && des!=NULL);
int srcEnd = 0;
while(1)
{
if(src[srcEnd] != '\0')
srcEnd++;
else
break;
}
char* pdes = des;
while(1)
{
if(*pdes != '\0')
{
src[srcEnd] = *pdes;
srcEnd++;
pdes++;
}
else
{
src[srcEnd] = '\0';
break;
}
}
return src;
}
////////////////////////////////////
bool IsSubstring(char* src,char* des)
{
char* srcTemp = new char[strlen(src)+1];
strcpy(srcTemp,src);
srcTemp[strlen(src)] = '\0';
src = MyStrcat(src,srcTemp);
if(strstr(src,des) != NULL)
{
delete[] srcTemp;
return true;
}
else
{
delete[] srcTemp;
return false;
}
}
void main()
{
char src[20] = "abcdef" , des[20] = "bcdg";
if(IsSubstring(src,des))
cout<<"OK"<
else
cout<<"NO"<
strcpy(src, "abcdef"),strcpy(des,"bc");
if(IsSubstring(src,des))
cout<<"OK"<
else
cout<<"NO"<
}
/*
NO
OK
总结:可以看出,当src和des内存一样时,因为src一直在增长着,指向des的指针pdes将不知道到哪里结尾,导致出错。
*/
#include
#include
#include
using namespace std;
////////////////////////////////////
char* MyStrcat(char* src,char* des)
{
assert(src!=NULL && des!=NULL);
int srcEnd = 0;
while(1)
{
if(src[srcEnd] != '\0')
srcEnd++;
else
break;
}
char* pdes = des;
while(1)
{
if(*pdes != '\0')
{
src[srcEnd] = *pdes;
srcEnd++;
pdes++;
}
else
{
src[srcEnd] = '\0';
break;
}
}
return src;
}
////////////////////////////////////
bool IsSubstring(char* src,char* des)
{
char* srcTemp = new char[strlen(src)+1];
strcpy(srcTemp,src);
srcTemp[strlen(src)] = '\0';
src = MyStrcat(src,srcTemp);
if(strstr(src,des) != NULL)
{
delete[] srcTemp;
return true;
}
else
{
delete[] srcTemp;
return false;
}
}
void main()
{
char src[20] = "abcdef" , des[20] = "bcdg";
if(IsSubstring(src,des))
cout<<"OK"<
else
cout<<"NO"<
strcpy(src, "abcdef"),strcpy(des,"bc");
if(IsSubstring(src,des))
cout<<"OK"<
else
cout<<"NO"<
}
/*
NO
OK
总结:可以看出,当src和des内存一样时,因为src一直在增长着,指向des的指针pdes将不知道到哪里结尾,导致出错。
*/