C ++ implements the split Function

Source: Internet
Author: User

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.

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.