1

I need a function that split a string in c, i write the code and I checked it, I didn't get any errors or warnings, the code is :

int main()
{
   cutString("any#any#any5") ;
    return 0;
}
void cutString(char  query[2000]) {
    char * cut ;
    cut = strtok(query , "#") ;
printf("%s" , cut);

}

But when I compile the program the compiler get stuck, without showing any output. This is a picture for run screen.

Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
Null Array
  • 47
  • 3
  • Both answers to this question omited one important fact: 'strtok' can not be used on constant strings because the function change it internally. If someone need tested working example please feel free to contact me by mail. – risbo Nov 17 '19 at 15:20

2 Answers2

1

Pay attention to the usage of strtok(). According to the Linux Man Page, on the first invocation of the function, you should specify the string to parse as first argument, while in each subsequent call you should specify NULL.

In fact, a sequence of calls on the same string maintains a pointer to the next character to process. If you want to check if no more tokens are found, just look at the return value (it'd be NULL in that case).

Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31
1

First of all you should read about the usage of strtok()

Please keep in mind you can't use strtok() on a string literal, since it will attempt to modify it which will cause undefined behavior.

#include <stdio.h>
#include <string.h>
int main()
{
    char toCut[100] = "to#cut#this";
    cutString(toCut);
    return 0;
}
void cutString(char* query) {
    char* cut ;
    cut = strtok(query, "#"); // this first call returns a pointer to the first substring
    while(cut != NULL)
    {
        printf("%s\n", cut);
        cut = strtok(NULL, "#"); // each call to strtok returns a pointer to the next substring
    }
}
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24