Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- char* sp = NULL; /* the start position of the string */
- char* strtok1(char* str, const char* delimiters) {
- int i = 0;
- int len = strlen(delimiters);
- /* check in the delimiters */
- if(len == 0)
- printf("delimiters are empty\n");
- /* if the original string has nothing left */
- if(!str && !sp)
- return NULL;
- /* initialize the sp during the first call */
- if(str && !sp)
- sp = str;
- /* find the start of the substring, skip delimiters */
- char* p_start = sp;
- while(1) {
- for(i = 0; i < len; i ++) {
- if(*p_start == delimiters[i]) {
- p_start ++;
- break;
- }
- }
- if(i == len) {
- sp = p_start;
- break;
- }
- }
- /* return NULL if nothing left */
- if(*sp == '\0') {
- sp = NULL;
- return sp;
- }
- /* find the end of the substring, and
- replace the delimiter with null */
- while(*sp != '\0') {
- for(i = 0; i < len; i ++) {
- if(*sp == delimiters[i]) {
- *sp = '\0';
- break;
- }
- }
- sp ++;
- if (i < len)
- break;
- }
- return p_start;
- }
- /* https://fengl.org/2013/01/01/implement-strtok-in-c-2/ */
- /* // ULtra-simple. haha! */
- /* // ------------------------------------------- */
- /* char* strtok1(char *str, const char* delim) { */
- /* static char* _buffer; */
- /* if(str != NULL) _buffer = str; */
- /* if(_buffer[0] == '\0') return NULL; */
- /* char *ret = _buffer, *b; */
- /* const char *d; */
- /* for(b = _buffer; *b !='\0'; b++) { */
- /* for(d = delim; *d != '\0'; d++) { */
- /* if(*b == *d) { */
- /* *b = '\0'; */
- /* _buffer = b+1; */
- /* // skip the beginning delimiters */
- /* if(b == ret) { */
- /* ret++; */
- /* continue; */
- /* } */
- /* return ret; */
- /* } */
- /* } */
- /* } */
- /* return ret; */
- /* } */
- int main ()
- {
- char str[] ="- This, a sample string.";
- char * pch;
- printf ("Splitting string \"%s\" into tokens:\n",str);
- pch = strtok1(str," ,.-");
- while (pch != NULL)
- {
- printf ("%s\n",pch);
- pch = strtok1(NULL, " ,.-");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement