c++ - calculate length of a string without using standard library funcions(like strlen) or indexing operator [] -
i have started learn c++. want clear no homework question, stuck on.
i going through assignment questions on mit website, , have pasted question here;
write function returns length of string (char *), excluding final null character. should not use standard-library functions. may use arithmetic , dereference operators,but nottheindexing operator([]).
i don't know how without array.
any appreciated!!
this did:
#include<iostream> #include<conio.h> #include<string> using namespace std; int stringlength (char* numptr); int main() { char *mystring; cout<<"enter string \n"; cin>>mystring; cout<<"length "<<stringlength(mystring); getch(); } int stringlength (char* numptr) { int count=0; for(;*numptr<'\0';*numptr++) { count++; } return(count); } had done before asked u problem. got me answer of zero. if in function change *numptr<'\0' *numptr!= 0, right answer. confused is, isn't null character, why cant check that.
first of all, not way learn c++ in 2013. answer relies on low-level pointer manipulation. there lot more important things learn c++ before point. right now, should learning string, vector, functions, classes, , not these low-level details.
to answer question, have know how strings represented. represented array of characters. in c , c++, arrays not have built in length. have store or use other means of finding length. way strings make can find length store 0, last position in array. "hello" stored
{'h','e','l','l','o',0}
to find length go through array starting @ index 0 , stop when encounter character value of 0;
the code this
int length(const char* str){ int = 0; for(; str[i] != 0; i++); return i; }
now in c , c++ can str[i] same *(str + i); satisfy question can write this
int length(const char* str){ int = 0; for(; *(str + i) != 0; i++); return i; }
now, instead of using + i, can increment str directly;
int length(const char* str){ int = 0; for(; *str++ != 0; i++){; return i; }
now in c, value false if 0, otherwise true, not need != 0, can write
int length(const char* str){ int = 0; for(; *str++; i++){; return i; }
Comments
Post a Comment