Article Source https://blog.csdn.net/glmushroom/article/details/80690881
Prior to use in C # Total division string using the system to function, for example:
string a = "This is a test";
string[] strArray = a.Split(' ');
In C ++, there is no direct string partition function, can use the function package C is a stroke segmentation:
. 1 Vector < string > Split ( const string & STR, const string & the delim) { 2 Vector < string > RES; . 3 IF ( "" == STR) return RES; . 4 // first string is to be cut from the string type conversion of type char * . 5 char * = STRs new new char [str.length () + . 1 ]; // do not forget . 6 strcpy (STRs, str.c_str ()); . 7 . 8 char * D = new new char[delim.length () + . 1 ]; . 9 strcpy (D, delim.c_str ()); 10 . 11 char * P = strtok (STRs, D); 12 is the while (P) { 13 is String S = P; // division the resulting string is converted to a string type 14 res.push_back (S); // into the result array 15 P = strtok (NULL, D); 16 } . 17 18 is return RES; . 19 }
To use the following call partition function:
The original string is the string of data transmission to other C # project
1 string str1 = "M135buffer.buffer,|M135data.data1,4.22424|M135data.data6,-0.0714111|M135data.data7,-0.53833|M135data.data11,145.569|M135data.data16,5.0354|M135data.data17,-112.906|M135data.data21,4.34509|M135data.data22,-0.115356|M135data.data23,0|M135data.data24,-14|M135data.data25,49521|M135data.data_lng,0|M135data.data26,-14|M135data.data27,49521|M135data.data_lati,0"; 2 string str2 = "|This is a test!\n"; 3 4 string str = str1+str2; 5 6 printf(str.c_str()); 7 8 vector<string> AllStr = split(str,"|"); 9 for (int i=0; i<AllStr.size();i++) 10 { 11 vector<string> tempStr = split(AllStr[i],","); 12 if(tempStr.size()>=2) 13 { 14 printf("Name:%s Value:%s\n",tempStr[0].c_str(),tempStr[1].c_str()); 15 } 16 }
Results are as follows:
note:
This split second partition function parameters can be passed more than a char, may pass a short string, but the function will be divided according to each string char,
C # -like partition function to pass a plurality of parameters str.Split ( '|', ',');
So: The partition function can only be a single or a plurality of individual char char divides, not in a direct short string segmentation.
----------------
Disclaimer: This article is the original article CSDN bloggers "glmushroom", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/glmushroom/article/details/80690881