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?
Asked
Active
Viewed 1,859 times
2 Answers
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
-
Thanks for answering. I will use `strchr` , which has as argument the token, not the position i. – pole gar Sep 21 '16 at 08:38
-
You do not change `ch` in the loop, so it is an endless loop. – mch Sep 21 '16 at 08:39
-
@polegar this should work strchr is taking two arguments the pointer and the character you are looking for in the string – Prashant Negi Sep 21 '16 at 08:46
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
-
This approach is a memory leak as the allocated `tokenized` is not certainly recoverable for a later `free()`. – chux - Reinstate Monica Sep 21 '16 at 16:34
-
-
"I can add a free after all" --> It is not that simple as code returns a pointer into allocated memory, but has lost the beginning of it. Suggest posting an answer that uses your "add a free" idea. – chux - Reinstate Monica Sep 21 '16 at 16:48
-
-
Using `strtok(string)` on a `const char *` is undefined behavior. Try coding it and see if your well enabled compiler warns. – chux - Reinstate Monica Sep 21 '16 at 17:34