C + + string-splitting functions

Source: Internet
Author: User

Original:

The C + + string does not have a split function, so it needs to be written conveniently. And by the development of tools, there are a lot of trouble to use it, the following is quite good Austrian.

The segmentation of strings by using STL


Two functions involving the string class find and substr:
1. Find function
Prototype: size_t find (const string& str, size_t pos = 0) const;
Function: Finds the position where the substring first appears.
Parameter description: STR is a substring and POS is the initial find location.
Return value: If found, returns the first occurrence of the position, otherwise returns String::npos


2. substr function
Prototype: String substr (size_t pos = 0, size_t n = npos) const;
function: Gets substring.
Parameter description: POS is the starting position (default is 0), n is the end position (default is NPOs)
return value: substring


The implementation is as follows:

/*
File:split1.cpp
Author:mike
e-mail: [Email protected]
*/
#include <iostream>
#include <string>
#include <vector>

String splitting function
Std::vector<std::string> Split (std::string str,std::string pattern)
{
Std::string::size_type POS;
std::vector<std::string> result;
str+=pattern;//extending strings for ease of operation
int size=str.size ();

for (int i=0; i<size; i++)
{
Pos=str.find (Pattern,i);
if (pos<size)
{
std::string s=str.substr (i,pos-i);
Result.push_back (s);
I=pos+pattern.size ()-1;
}
}
return result;
}

int main ()
{
std::string str;
std::cout<< "Please input str:" <<std::endl;
std::cin>>str;
Getline (STD::CIN,STR);
Std::string pattern;
std::cout<< "Please input pattern:" <<std::endl;
std::cin>>pattern;
Getline (Std::cin,pattern);//used to get a string with spaces
Std::vector<std::string> Result=split (Str,pattern);
std::cout<< "The result:" <<std::endl;
for (int i=0; i<result.size (); i++)
{
std::cout<<result[i]<<std::endl;
}

Std::cin.get ();
Std::cin.get ();
return 0;
}

C + + string-splitting functions

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.