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