pole gar
pole gar

Reputation: 63

Iterating string with strchr in C

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?

Upvotes: 0

Views: 2125

Answers (2)

pole gar
pole gar

Reputation: 63

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;
}

Upvotes: 0

Prashant Negi
Prashant Negi

Reputation: 348

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,';');
}

Upvotes: 3

Related Questions