简体   繁体   中英

Get one specific token of string in C

I have a file that has text inside it ( <tab> is \\t ):

display <tab> output_stmt
[ <tab> left_bracket
"Hello World" <tab> string_const
] <tab> right_bracket
~ <tab> term_sym

How can I get the strings after the <tab> , skipping the first string and <tab> everyline.

I only know how to get only the first string and ignore the rest of the line by using:

strtok(variablename, "\t");

Any useful answers are much appreciated.
Thank you!

With the strtok() function you can get also the next token. See the man page of strtok() :

The strtok() function breaks a string into a sequence of zero or more nonempty tokens. On the first call to strtok() the string to be parsed should be specified in str . In each subsequent call that should parse the same string, str must be NULL .

So you can call:

char* tokenOne = strtok(variablename, "\t"); /* first token  */
char* tokenTwo = strtok(NULL, "\t");         /* second token */

Note that you don't have to free memory because strtok() works with the input buffer as it changes it eg:

"display \t output_stmt\0"

will be:

"display \0 output_stmt\0"

after the call of strtok() . After that it just returns a pointer to the next token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM