- 论坛徽章:
- 0
|
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <iterator>
- using namespace std;
- /*! From a string, extract all sub-strings separated by the delimiters
- * and append them to a vector container.
- */
- void split_string( const string& str, const string& delims,
- vector<string>& str_vector );
- int main()
- {
- const string test_str = "kevin:pass@127.0.0.1:/var/path/kevin/demo.cpp";
- vector<string> vs; // used to save the extracted sub-strings.
- // Get the sub-strings separated by ':' or '@'.
- split_string( test_str, ":@", vs );
- // Separate the path and file name.
- string::size_type pos = vs.back().rfind('/');
- vs.push_back( vs.back().substr( pos + 1 ) );
- vs[vs.size() - 2].erase( pos );
- // Output the extracted sub-strings.
- cout << "Number of extracted sub-string: " << vs.size() << "\n\t";
- copy( vs.begin(), vs.end(), ostream_iterator<string>(cout, "\n\t") );
- }
- void split_string( const string& str, const string& delims,
- vector<string>& str_vector )
- {
- string::size_type pos_prev = 0;
- string::size_type pos;
- while ((pos = str.find_first_of( delims, pos_prev )) != string::npos) {
- str_vector.push_back( str.substr(pos_prev, pos - pos_prev) );
- pos_prev = pos + 1;
- }
- str_vector.push_back( str.substr(pos_prev) );
- }
复制代码 |
|