0

If I have a string like char str [] = "hello;people;how;are;you" and use strchr(str,";") how can I take the N-th token of the string?

pole gar
  • 53
  • 9

2 Answers2

3

Suppose you are storing the strchr in a char * ch

Then ch-str+1 will return you the position of the character that you looked for in strchr

Using a predefined substring function or defining a function of your own you can create a while loop like this :

i=0;
while(ch != NULL)
{
    printf("Your subsrting is : %s", substring_function(i,(ch-str+1)));
    i = ch-str+1;
    ch=strchr(ch+1,';');
}
Prashant Negi
  • 348
  • 2
  • 14
0

OK, found a solution with strtok and I'd like to convert it using strchr. Tokenizer is static variable which contains the character for tokenizing. Any ideas?

static const char *a(const char *string,int tkn) {
    char *tokenized=strdup(string);
    char *token;
    token=strtok(tokenized, tokenizer);
    int i=0;
    while(token != NULL) {
      if (i == (tkn-1)) {
        break;
      }
      token = strtok(NULL, tokenizer);
      i++;
   }
   return token;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
pole gar
  • 53
  • 9