C ++ string split

Source: Internet
Author: User

# Include <string>
# Include <vector>

Namespace daniweb
{
Using namespace STD;

Typedef string: size_type (string: * find_t) (const string & delim,
String: size_type offset) const;

/// <Summary>
/// Splits the string s on the given delimiter (s) and
/// Returns a list of tokens without the delimiter (s)
/// </Summary>
/// <Param name = s> the string being split </param>
/// <Param name = match> the delimiter (s) for splitting </param>
/// <Param name = removeempty> Removes empty tokens from the list </param>
/// <Param name = fullmatch>
/// True if the whole match string is a match, false
/// If any character in the match string is a match
/// </Param>
/// <Returns> A list of tokens </returns>
Vector <string> split (const string & S,
Const string & match,
Bool removeempty = false,
Bool fullmatch = false)
{
Vector <string> result; // return container for tokens
String: size_type start = 0, // starting position for searches
Skip = 1; // positions to skip after a match
Find_t pfind = & string: find_first_of; // Search Algorithm for matches

If (fullmatch)
{< br> // use the whole match string as a key
// instead of individual characters
// skip might be 0. see search loop comments
skip = match. length ();
pfind = & string: Find;
}

While (start! = String: NPOs)
{
// Get a complete range [start... end)
String: size_type end = (S. * pfind) (match, start );

// Null strings always match in string: Find,
// A skip of 0 Causes infinite loops. Pretend that
// No tokens were found and extract the whole string
If (skip = 0) End = string: NPOs;

String token = S. substr (START, end-Start );

If (! (Removeempty & token. Empty ()))
{
// Extract the token and add it to the result list
Result. push_back (token );
}

// Start the next range
If (START = END )! = String: NPOs) Start + = skip;
}

Return result;
}
}

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.