我想创建自己的strlen和substr函数,并且我有1个问题。
例如,假设我有字符串ABC,我的strlen将返回3,让我说我想从0到1剪切这个字符串它应该返回给我A,但我得到一些垃圾值,如果我插入substr到一个新的字符,并检查长度我将收到14
这是我的代码:
创建我自己的strlen和子字符串函数
int len(char *w){
int count=0;
int i=0;
while (w[i]!='\0')
{
count++;
i++;
}
//cout<<"Length of word is:"<<count<<"\n";
return count;
}
char *subs(char *w,int s,int e){
int i,j;
int size=0;size=(e-s);
//cout<<"new size is:"<<size<<"\n";
char *newW=new char[size];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
return newW;
}
int main(){
char* x="ABC";
//int v=len(x);
//cout<<v;
char *n=subs(x,0,1);
cout << len(n);
for(int g=0;g<len(n);g++)
//cout<<n[g];
return 0;
}
我想获得一些意见我做错了什么,谢谢!
你试过调试吗? –
您需要在末尾加上'\'0'。你需要确保它有足够的空间。 – BoBTFish
确保在使用后删除[]你的char数组。 – urzeit