Search code examples
cstringstrtok

About strtok and tokens in C


so i have a question about strtok in C.Is it possible to use strtok to reform a string without the specific token u remove from it ?For example i have a string that i get from main with argc,argv.

void main(int argc,char *argv[]){
//so i get the string ok let's say its the string my-name-is-Max
//so i want to strtok with "-" so i get the string without the "-" 
//the prob is i can;t seem to reform the string meaning making it 
mynameisMax 

// its just "Max" or "my" sometimes , is there a way i can like combine them 
//together using token method ? 
}

Solution

  • strtok is an overkill for finding a single character. And does not serve you right in this case. If you want to overwrite your arguments then just use strchr and memmove (because it's overlapping memory) or strpbrk if you search for a range of characters.

    char* s = argv [i];
    char* d = argv [i];
    char* pos;
    
    while ((pos = strchr (s, '-')) != NULL)
    {
        memmove (d, s, pos-s); /* Copy (overlapping) all but the dash */
        d += pos-s;            /* Advance the destination by the copied text. */
        s = pos+1;             /* Advance the source past the dash */
    }
    memmove (d, s, strlen (s) + 1); /* Copy the rest of the string including the NULL termination. */