Monday, April 1, 2013

The most elegant way to split a string in C++

1. Splitting a string in C++




#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "Splitting a string in C++...";
    istringstream iss(sentence);
    copy(istream_iterator<string>(iss),
             istream_iterator<string>(),
             ostream_iterator<string>(cout, "\n"));
}

OUTPUT:
Splitting
a
string
in
C++...

2. Splitting a String using a delimiter



#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

vector<string> split(const string& s, const string& delim, const bool keep_empty = true) {
    vector<string> result;
    if (delim.empty()) {
        result.push_back(s);
        return result;
    }
    string::const_iterator substart = s.begin(), subend;
    while (true) {
        subend = search(substart, s.end(), delim.begin(), delim.end());
        string temp(substart, subend);
        if (keep_empty || !temp.empty()) {
            result.push_back(temp);
        }
        if (subend == s.end()) {
            break;
        }
        substart = subend + delim.size();
    }
    return result;
}

int main() {
    const vector<string> words = split("Splitting a String using a delimiter", " ");
    copy(words.begin(), words.end(), ostream_iterator<string>(cout, "\n"));
}


OUTPUT:
Splitting
a
String
using
a
delimiter




---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------




---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
-----------------------------------------------------------------------

C++ split string
Split String for C++ Split String‎ 
divide string into small strings‎ 
Splitting strings‎ 
Breaking a string into tokens‎ 
Splitting a String using a delimiter
Splitting a string into tokens using strtok and string as 
C++ Split function?‎ 
Split string into array of strings‎ 
Splitting and saving strings in an array
C++: Split string at certain position.Searches related to how to split a string in c++ split string array c++ split string java split string visual basic split string python split cstring split char c++ c++ split string by delimiter system string split c++

No comments:

Post a Comment