创建我自己的strlen和子字符串函数

Create my own strlen and substring functions

本文关键字:字符串 函数 strlen 我自己 自己的 创建      更新时间:2023-10-16

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

int len(char *w){
    int count=0;
    int i=0;
    while (w[i]!='')
    {
        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;
}

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

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

子字符串应以"\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] = '';
    return newW;
}