Use of strtok Functions

Source: Internet
Author: User
Tags strtok

Go to strtok:

Usage: token = strtok (source-STR, seperator-Str)
Purpose: in source-STR, find the character string separated by the characters in seperator-STR, that is, the string of the remaining segments after the source string contains all the characters in the separator string, each call finds a string. If no string is found, an empty string is returned.
Note: The Return Value refers to the pointer to the source string, so the validity of the source string must also be ensured, each time a substring is returned, the tail character (originally a character in the search string) of the substring in the source string is changed to the '/0' character. Another thing to note is that this function uses a Global static buffer (the function's own static buffer), so do not call this function to process two strings at the same time in a thread, otherwise, it is easy to see abnormal results. The correct solution is to first find all the substrings in a string and then convert them to another string. This interference does not occur between multiple threads.
The following is an example in msdn:
Data preparation:
Char string [] = "A String/TOF, tokens/NAND some more tokens ";
Char SEPs [] = ",/T/N ";
Char * token;
Call example:
Token = strtok (string, SEPs );
While (Token! = NULL)
{
/* While there are tokens in "string "*/
Printf ("% s/n", token );
/* Get next token :*/
Token = strtok (null, SEPs );
/* Note that the above null indicates that the remaining substring is retrieved from the buffer zone of strtok In the last call result */
}
Display result:
A // string [1] = '/0' at this time, which is originally a space
String
Of
Tokens
And
Some
More
Tokens

 

 

Experiment Program:

# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Int main ()
{
Char string [] = "a string of, tokens % and some more tokens ";
Char SEPs [] = "%/N ";
Char * token;
Token = strtok (string, SEPs );
While (Token! = NULL)
{
Printf ("% s/n", token );
Token = strtok (null, SEPs );
}
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.