Strtok and Strtok_r

Source: Internet
Author: User
Tags strtok

Strtok and Strtok_r

Prototype: Char *strtok (char *s, char *delim);

Function: Decomposes a string into a set of strings. S is the string to be decomposed, Delim is the delimiter string.

Description: On first call, S points to the string to be decomposed, and then calls to set S to null.
Strtok finds the characters included in the Delim in S and replaces them with null ('/0 ') until the entire string is searched.

return value : The cut string from the start of S. Returns NULL when there are no strings to be cut.
All the characters included in the Delim will be filtered out and set to a cut node where it is filtered.

Example:

#include <string. h>
#include <stdio.h>

int main (void )
{
Char input[] = "abc,d" ;
Char * P

/* strtok places a NULL Terminator
In front of the token, if found * /
P = strtok (input, "," );
if (p) printf ("%s " , p);

/* A second call to Strtok using A NULL
As the first parameter returns a pointer
To the character following the token * /
P = strtok (NULL, "," );
if (p) printf ("%s " , p);

return 0 ;
}

The first call of the function sets two parameters. The result of the first cut returns the string before the first ', ', which is the first output ABC of the above program.

The second time the function is called strtok (null, "."), the first parameter is set to NULL. The result is a cut based on the following string, that is, the second output d.

Functions with _r come mainly from the following UNIX. The difference between all the functions with _r and without _r is that the function with _r is thread-safe, and R means reentrant, which can be re-entered.

1. Strtok Introduction
As is known to all, Strtok can be based on user-provided cutting characters (the same time the delimiter can be a plural analogy ",. ”)
Cuts a string until "/0" is encountered.

For example, delimiter = "," string = "Fred,john,ann"
The 3 string "Fred" "John" "Ann" can be extracted by strtok.
The C code above is

Quote:int in=0;
Char buffer[]= "Fred,john,ann"
Char *p[3];
char *buf = buffer;
while ((P[in]=strtok (buf, ","))!=null) {
in++;
Buf=null; }

As shown in the code, the first run of Strtok requires the address of the target string to be the first (Buf=buffer), after which the strtok needs to be NULL for the first (buf=null) parameter. Pointer column p[], the result of the cut is stored, p[0]= "John", p[1]= "John", p[2]= "Ann", and Buf becomes fred/0john/0ann/0.

2. Strtok's weaknesses
Let's change our plan: We have a string "Fred male 25,john male 62,anna female 16" We want to sort this string into a struct,

Quote:struct Person {
char [+] name;
char [6] sex;
Char [4] age;
}

One way to do this is to first extract a string of "," cut, and then cut it with "" (space).
For example: Intercept "Fred male 25" and then cut to "Fred" "Male" "25"
Below I have written a small program to show this process:

QUOTE: #include <stdio.h>
#include <string.h>
#define INFO_MAX_SZ 255
int main ()
{
int in=0;
Char buffer[info_max_sz]= "Fred male 25,john male 62,anna female 16";
Char *p[20];
Char *buf=buffer;

while ((P[in]=strtok (buf, ","))!=null) {
Buf=p[in];
while ((P[in]=strtok (buf, ""))!=null) {
in++;
Buf=null;
}
p[in++]= "* * *"; Performance Cutting
Buf=null; }

printf ("Here we have%d strings/n", i);
for (int j=0; j<in; j + +)
printf (">%s</n", P[j]);
return 0;
}

The output of this program is:
Here we have 4 strings
>Fred<
>male<
>25<
>***<
This is just a small piece of data, not what we need. But why is that? This is because Strtok uses a static (static) pointer to manipulate the data, let me analyze the execution of the above code:

RedFor the Strtokwhere the built-in pointer points,BlueFor Strtok to String.Changes

1. "FRed male 25,john male 62,anna female 16 "//Outer loop

2. "Fred male 25/0JOhn Male 62,anna Female 16 "//Enter Inner loop

3. "Fred/0mAle 25/0john Male 62,anna female 16 "

4. "Fred/0male/025/0john male 62,anna Female 16 "

5 "fred/0male/025/0John male 62,anna Female 16 "//Inner Loop encountered"/0 "back to outer loop

6 "fred/0male/025/0John male 62,anna Female 16 "//outer loop encounters the end of"/0 "execution.

3. Using Strtok_r
In such a case we should use Strtok_r, Strtok reentrant.
Char *strtok_r (char *s, const char *delim, char **ptrptr);

Relative strtok we need to provide a pointer to strtok to operate, rather than using a companion pointer like Strtok.
Code:

QUOTE: #include <stdio.h>
#include <string.h>
#define INFO_MAX_SZ 255
int main ()
{
int in=0;
Char buffer[info_max_sz]= "Fred male 25,john male 62,anna female 16";
Char *p[20];
Char *buf=buffer;

Char *outer_ptr=null;
Char *inner_ptr=null;

while ((P[in]=strtok_r (buf, ",", &outer_ptr))!=null) {
Buf=p[in];
while ((P[in]=strtok_r (buf, "", &inner_ptr))!=null) {
in++;
Buf=null;
}
p[in++]= "* * *";
Buf=null; }

printf ("Here we have%d strings/n", i);
for (int j=0; jn<i; j + +)
printf (">%s</n", P[j]);
return 0;
}

This time the output is:
Here we have a strings
>Fred<
>male<
>25<
>***<
>John<
>male<
>62<
>***<
>Anna<
>female<
>16<
>***<


Let me examine the execution of the above code:

RedFor the Strtok_rlocation of the outer_ptr point,
PurpleFor the Strtok_rlocation of the inner_ptr point,
BlueFor Strtok to String.Changes

1. "FRed male 25,john male 62,anna female 16 "//Outer loop

2. "FRed Male 25/0JOhn Male 62,anna Female 16 "//Enter Inner loop

3. "Fred/0mAle 25/0JOhn Male 62,anna Female 16 "

4 "Fred/0male/025/0JOhn Male 62,anna Female 16 "

5 "fred/0male/025/0JOhn Male 62,anna Female 16 "//Inner Loop encountered"/0 "back to outer loop

6 "fred/0male/025/0JOhn Male 62/0ANNA female 16 "//Enter Inner loop

Strtok and Strtok_r

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.