2013-07-11 57 views
-3

我想创建自己的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; 
} 

我想获得一些意见我做错了什么,谢谢!

+3

你试过调试吗? –

+0

您需要在末尾加上'\'0'。你需要确保它有足够的空间。 – BoBTFish

+0

确保在使用后删除[]你的char数组。 – urzeit

回答

1

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

1

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

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