Search code examples
cpointersstrtok

How strtok works?


#include <stdio.h>
#include<string.h>

int main() {
    char a[]="hey -* there -* minecraft-; jukebox! ";
    char *p=strtok(a,"-");
    //printf("%s",a);        --line-id(00)
    while(p!= NULL)
    {
        printf("%s",p);      //line-id(01)
        p=strtok(NULL,"-");
    }
    printf("\n");
    p=strtok(a,"*");
    while(p!=NULL)
    {
        printf("%s",p);
        p=strtok(NULL,"*");
    }
    return 0;
}

output:

hey * there * Minecraft; jukebox! 
hey 

But my required output is:

hey * there * Minecraft; jukebox! 
hey there Minecraft jukebox!

Q) why I can't change the line-id(01) to print("%s",*p) since p is a pointer we should use *p to get the value, p pointing to right..? I'm getting a segmentation fault.

Q)if i use print("%s",a) I'm getting hey as output in line-id(00); why?

Q) If possible explain the pointer p used in strtok(). how strtok works?


Solution

  • Another option to remove delimiters from a char array is to overwrite the delimiter with subsequent characters, contracting the array.

    #include <stdio.h>
    #include<string.h>
    
    int main() {
        char a[]="hey -* there -* minecraft-; jukebox! ";
        char delimeters[] = "-*;";
        char *to = a;
        char *from = a;
    
        for ( int each = 0; each < 3; ++each) {//loop through delimiters
            to = a;
            from = a;
            while ( *from) {//not at terminating zero
                while ( *from == delimeters[each]) {
                    ++from;//advance pointer past delimiter
                }
                *to = *from;//assign character, overwriting as needed
                ++to;
                ++from;
            }
            *to = 0;//terminate
            printf ( "%s\n", a);
        }
        return 0;
    }
    

    output

    hey * there * minecraft; jukebox! 
    hey  there  minecraft; jukebox! 
    hey  there  minecraft jukebox!