For the reason of today's work, we need to implement a split function. We have done it before, but we have never written it down, so I wrote it again. This time I made a note for later use. You can also use it directly if you are interested.
Example:
A string like this: "123,456,789, 0 ". Truncates A String Array [123], [456], [789], and [0]. As we all know, C ++ does not provide such a function by default. We will implement it ourselves.
Not to mention the Code directly:
Code
# Include <iostream>
# Include <string>
# Include <vector>
Using namespace STD;
Vector <string> splitex (const string & SRC, string separate_character)
{
Vector <string> STRs;
Int separate_characterlen = separate_character.size (); // you can separate the length of a string, such as "," and ".
Int lastposition = 0, Index =-1;
While (-1! = (Index = SRC. Find (separate_character, lastposition )))
{
STRs. push_back (SRC. substr (lastposition, index-lastposition ));
Lastposition = index + separate_characterlen;
}
String laststring = SRC. substr (lastposition); // extract the content after the last Separator
If (! Laststring. Empty ())
STRs. push_back (laststring); // enter the queue if there is content after the last Separator
Return STRs;
}
Int _ tmain (INT argc, _ tchar * argv [])
{
String S = "123,456,789, 0,888 ";
String del = ",";
Vector <string> STRs = splitex (S, del );
For (unsigned int I = 0; I <STRs. Size (); I ++)
{
Cout <STRs [I]. c_str () <Endl;
}
Return 0;
}
Output:
123
456
789
0
888
PS: it is purely for personal use and has not been strictly tested. There may be some things out of consideration. You are welcome to point out.