首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++的一个代码,有个细节搞不懂解决方法

2012-06-01 
c++的一个代码,有个细节搞不懂#include iostream#include stringusing namespace stdint next[20]ch

c++的一个代码,有个细节搞不懂
#include <iostream>
#include <string>
using namespace std;
int next[20];
char str[100],a[20];
int lenstr,lena;
void Getnext(char a[])
{
int i = 0,j = -1;
next[0] = -1;
cout<<"a长度:"<<strlen(a)<<endl;
while( i < strlen(a))
{
if(j == -1 || a[i] == a[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
//for(i = 0; i < strlen(a); i++)cout<<next[i];cout<<endl;
}
int KMP(char str[],char a[])
{
int i = 0, j = -1;
while( i < strlen(str) && j < strlen(a))
{
if(j == -1 || str[i] == a[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
cout<<"a长度:"<<strlen(a)<<endl;
cout<<"str长度:"<<strlen(str)<<endl;
if(j == strlen(a))return i - lena + 1;
else
return -1;
}
int main()
{
memset(next,0,sizeof(next));
char str[100],a[20];
cin>>str;
cin>>a;
lenstr = strlen(str);
lena = strlen(a);

Getnext(a);
int pos = KMP(str,a);
cout<<pos<<endl;
return 0;
}
这是个KMP算法的代码,主要不是算法搞不明白,是串str 和 a 的长度 用 
lenstr 和lena 与 strlen(str)和strlen(a)互换,结果就不一样
 我想问的是,在c++函数里 假如实参是串,函数里用strlen 会出错吗
  直接传过来一个串的长度的实参肯定不会错,但在串里动态的用strlen就错了吗
 结果很是令我费解啊

[解决办法]
strlen()计算长度时'\0'就结束,工的内容被改变后很有可能'\0'出现在了a字符串的某中间位置,而不在结尾了。所以计算出来的长度是不准的。
[解决办法]
同学,我知道是什么原因了

C/C++ code
int i = 0, j = -1;while( i < strlen(str) && j < strlen(a)) 

热点排行
Bad Request.