i trying create own strlen , substr functions , have 1 problem.
example, let have string abc, strlen return 3, let want cut string 0 1 should return me a,but trash values, if insert substr new char , check length recieve 14.
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 comments did wrong, thanks!
change condition loop for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++)
, need allocate size +1 since have add \0 @ end of string.
Comments
Post a Comment