Create my own strlen and substring functions

99封情书 提交于 2019-12-08 14:20:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!