Implementation of strsep Function C Language

Source: Internet
Author: User
Prototype: char * strsep (char ** stringp, const char * delim );

Function: Splits a string into a group of strings.

Example:

# Include <stdio. h>

# Include <string. h>

Int main (void)

{

Char STR [] = "root: X: 0: Root:/root:/bin/Bash :";

Char * Buf;

Char * token;

Buf = STR;

While (token = strsep (& Buf ,":"))! = NULL ){

Printf ("% s \ n", token );

}

Return 0;

}

Another exampleProgram:

# Include <stdio. h>

# Include <string. h>

Void main ()

{

Char STR [] = "number = 100 & maxmtu = 200 ";

Char * Name, * value, * next;

Int I;

Value = STR; // point the pointer value to the string STR;

For (I = 0; I <2; I ++)

{// At the first execution

Name = strsep (& value, "="); // splits the string with "=". Then, the return value of the strsep function is "Number", that is, the string before "= ".

Next = value; // the pointer value points to the string after "=", that is, "100 & maxmtu = 200"

Value = strsep (& next, "&"); // in this case, use "&" to separate the string. The returned value is 100. Next indicates "maxmtu = 200"

Printf ("name = % s \ n", name); // print the value of name after one split

Printf ("value = % s \ n", value );

Value = next;

}

}

The execution result is:

Name = Number

Value = 100

Name = maxmtu

Value = 200

The C language is implemented as follows:

 
Char * strsep (char ** STR, const char * delims) {char * token; If (! * Str) {/* No more tokens */return NULL;} token = * STR; while (** Str! = '\ 0') {If (strchr (delims, ** Str) {** STR =' \ 0'; (* Str) ++; return Token ;} (* Str) ++;}/* There is no other token */* STR = NULL; return Token ;}

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.