c++ - I am attempting to create a strtok function from scratch using arrays -
i not sure go here. trying strtok function scratch using arrays. wanted store each token in temp array, print it, , keep doing many tokens array have. instance, string such "this fab" wanted "this", copied on temp until delimiter( null, or space or character) encountered. printed. final result of should have been:
this \n
is \n
fab \n
does have insight.
char strtok( char s[], char key) { char find; char temp[100] = " "; int = 0; while( s[i] != '\0') { i++; for(; s[find] != key && s[find] != '\0'; find++) { temp[i]= s[find]; } cout<<endl; } for( int x = 0; temp[x] != '\0'; x++) { cout<<temp[x]; } cout<<endl; }
standard strtok
defined follows:
char *strtok(char *str, const char *delim)
for homemade version, must return char*
. example below similar standard version uses char
delimiter.
see example of strtok
in first call function should setup variable. in subsequent calls should continue left off before.
char *homemade_strtok(char *arg, const char delimiter) { static int pos = 0; static char* buf = 0; static char* token = 0; if (arg) { //start new search pos = 0; buf = arg; //delete previous token if if (token) delete token; //create token @ least big argument token = new char[strlen(buf) + 1]; } if (!buf) return 0; if (pos >= strlen(buf)) return 0; //prepare token memset(token, 0, strlen(buf) + 1); int = 0; while (pos < strlen(buf)) { if (buf[pos] == delimiter) { pos++; return token; } token[i] = buf[pos]; i++; pos++; } return token; } int main() { char *buf = "hello world 1a 2b 3c"; char *token = homemade_strtok(buf, ' '); while (token) { std::cout << token << "\n"; token = homemade_strtok(null, ' '); } return 0; }
edited: fixed memory leak
Comments
Post a Comment