[A good way to split strings by TAG] strtok function introduction and application.

Source: Internet
Author: User
Tags strtok

Just getting started with the strtok function is amazing. Definition: strtok Syntax: # include <string. h> char * strtok (char * str1, const char * str2); Function. If the separator is not found, the function returns NULL. To convert a string into a tag, str1 is called for the first time as the tag separator. Therefore, all calls to str1 should be NULL. For example: [cpp] char str [] = "now # is the time for all # good men to come to the # aid of their country "; char delims [] = "#"; char * result = NULL; result = strtok (str, delims); while (result! = NULL) {printf ("result is \" % s \ "\ n", result); result = strtok (NULL, delims);} the result of this sample is: result is "now" result is "is the time for all" result is "good men to come to the" result is "aid of their country" implemented through '#' split purpose. Typical applications, such as HDU 1106: to open the question link, split the string by 5 and convert it to a string for sorting. The general method is direct simulation, but if you use the strtok function flexibly (note that its return value is a pointer) and the string is converted to the numeric function atoi (), this question is very simple. [Cpp] # include <iostream> # include <algorithm> # include <cstring> # include <string. h> # include <stdlib. h> using namespace std; bool cmp (int a, int B) {return a <B;} int num [1009]; int main () {char tar [1009]; while (cin> tar) {string numpack [1000]; memset (num, 0, sizeof (num); int pos = 0; int start = 0, end = 0; char * temp; temp = strtok (tar, "5"); // separate by 5 also while (temp! = NULL) {numpack [pos] = temp; temp = strtok (NULL, "5"); // basic usage: Save the pointer to the array pos ++ ;} for (int I = 0; I <pos; I ++) {num [I] = atoi (numpack [I]. c_str ();} sort (num, num + pos, cmp); for (int I = 0; I <pos; I ++) {cout <num [I]; if (I! = Pos-1) cout <"; else cout <endl ;}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.