创建我自己的strlen和substring函数

时间:2013-07-11 14:28:36

标签: c++ substr strlen

我正在尝试创建自己的strlen和substr函数,我有一个问题 例如,假设我有字符串ABC,我的strlen将返回3,假设我想将此字符串从0切换为1它应该返回给我A,但是我得到一些垃圾值,如果我将substr插入到新的字符并检查我将收到的长度14.
这是我的代码:

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;
}

我想得到一些评论,我做错了,谢谢!

2 个答案:

答案 0 :(得分:1)

更改for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++)的条件循环,您需要分配大小+1,因为您必须在字符串末尾添加\ 0。

答案 1 :(得分:1)

子字符串应以'\ 0'结尾,数组大小应加一。这是代码:

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;
}
相关问题