问题
I am trying to create my own strlen and substr functions and I have 1 problem.
for example, let say I have the string ABC, my strlen will return 3, let say I want to cut this string from 0 to 1 its should return to me A,but I get some trash values, if I insert the substr to a new char and check the length I will recieve 14.
this is my code:
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;
}
I would like to get some comments what I did wrong, Thanks!
回答1:
Change your condition loop for for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++)
and you need to allocate size +1 since you have to add a \0 at the end of the string.
回答2:
sub string should end with a '\0', the array size should add one. Here is the code:
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 + 1];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
newW[i] = '\0';
return newW;
}
来源:https://stackoverflow.com/questions/17596096/create-my-own-strlen-and-substring-functions