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

2014-11-23 23:18:24 · 作者: · 浏览: 12
<1>
方法1:循环遍历
[cpp] #include
#include
using namespace std;
bool IsSubstring(char* src,char* des)
{
int len = strlen(src);
for(int i = 0;i < len;i++)
{
if(strstr(src,des) != NULL)
return true;
char tempchar = src[0];
for(int j = 0;j < len -1;j++)
src[j] = src[j+1];
src[len - 1] = tempchar;
}
return false;
}
void main()
{
char src[20] = "abc" , des[20] = "bcd";
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
总结:
1,注意在IsSubstring里面,即使是char src[],也依然退化为指针,你用字符串常量就会出错
2,即使为char*,依然可以用strlen函数,因为它判断的是'\0',退化为指针后不能用sizeof
3,开始使用的是char[]全局变量的时候,注意分配内存的大小已经确定,以后在strcpy的时候注意别数组越界
*/
#include
#include
using namespace std;
bool IsSubstring(char* src,char* des)
{
int len = strlen(src);
for(int i = 0;i < len;i++)
{
if(strstr(src,des) != NULL)
return true;
char tempchar = src[0];
for(int j = 0;j < len -1;j++)
src[j] = src[j+1];
src[len - 1] = tempchar;
}
return false;
}
void main()
{
char src[20] = "abc" , des[20] = "bcd";
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
总结:
1,注意在IsSubstring里面,即使是char src[],也依然退化为指针,你用字符串常量就会出错
2,即使为char*,依然可以用strlen函数,因为它判断的是'\0',退化为指针后不能用sizeof
3,开始使用的是char[]全局变量的时候,注意分配内存的大小已经确定,以后在strcpy的时候注意别数组越界
*/方法2:将字符串s1换成s1s1,看s2是否为s1s1子串
[cpp] #include
#include
using namespace std;
bool IsSubstring(char* src,char* des)
{
char* srcTemp = new char[strlen(src)+1];
strcpy(srcTemp,src);
srcTemp[strlen(src)] = '\0';
src = strcat(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
总结:
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)是未定义的
*/
#include
#include
using namespace std;
bool IsSubstring(char* src,char* des)
{
char* srcTemp = new char[strlen(src)+1];
strcpy(srcTemp,src);
srcTemp[strlen(src)] = '\0';
src = strcat(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(sr