C-language string Separation

Source: Internet
Author: User
Tags strtok

strtok () this parameter is used to set character strings are separated into segments. The STR parameter points to the string to be split, and the delimiters parameter is the split string. When strtok () when the delimiters Delimiter is found in the STR string, the Delimiter is changed to '\ 0. In the first call, strtok () must be given the STR string parameter. In future calls, the STR set to null.



Split in C/C ++ Function Is strtok (). Its function prototype is as follows:


Char * strtok (char * STR, const char * delimiters );



Function Description


Strtok () is used to split strings into segments. The STR parameter points to the string to be split, and the delimiters parameter is the split string. When strtok () when the delimiters Delimiter is found in the STR string, the Delimiter is changed to '\ 0. In the first call, strtok () must be given the STR string parameter. In future calls, the STR parameter is set to null. If each call is successful, the next split string pointer is returned.



Return Value


Returns the string pointer after the next split. If no split exists, null is returned.




Example-1


/* Strtok example */


# Include <stdio. h>


# Include <string. h>



Int main ()


{


Char STR [] = "A, B, C, D * E ";


Const char * Split = ",";


Char * P;


P = strtok (STR, split );


While (P! = NULL ){


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


P = strtok (null, split );


}



Getchar ();


Return 0;



}


In this example, the strings 'a, B, c, d * E "are separated by commas (,) as delimiters.

Output The result is as follows:


A


B


C


D * E



Because delimiters supports multiple delimiters Statement Line


Const char * Split = ",";


Change to const char * Split = ", *"; // use commas (,) and asterisk (*) to separate strings.



The output result is as follows:


A


B


C


D


E

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.