2012-02-24 14 views
37

Jaka byłaby najłatwiejsza metoda podziału ciągu za pomocą C++ 11?Dzielenie ciągu znaków za pomocą C++ 11

Widziałem metodę używaną przez to post, ale uważam, że powinien istnieć mniej szczegółowy sposób robienia tego przy użyciu nowego standardu.

Edytuj: Chciałbym uzyskać w rezultacie vector<string> i być w stanie wytyczyć pojedynczą postać.

+1

Dzielenie na przestrzeni? I nie sądzę, że C++ 11 dodał coś tutaj, myślę [zaakceptowana odpowiedź] (http://stackoverflow.com/a/237280/845092) jest nadal najlepszym sposobem. –

+0

czego chcesz po podzieleniu? drukuj do cout? lub uzyskać wektor podciągów? – balki

+0

Czy nie jest to do czego służy parsowanie wyrażeń regularnych? –

Odpowiedz

4

Nie wiem, czy jest to mniej szczegółowe, ale może być łatwiej grok dla bardziej doświadczonych w dynamicznych językach, takich jak javascript. Jedyna funkcja C++ 11, której używa, to lambdas.

#include <algorithm> 
#include <string> 
#include <cctype> 
#include <iostream> 
#include <vector> 

int main() 
{ 
    using namespace std; 
    string s = "hello how are you won't you tell me your name"; 
    vector<string> tokens; 
    string token; 

    for_each(s.begin(), s.end(), [&](char c) { 
    if (!isspace(c)) 
     token += c; 
    else 
    { 
     if (token.length()) tokens.push_back(token); 
     token.clear(); 
    } 
    }); 
    if (token.length()) tokens.push_back(token); 

    return 0; 
} 
+14

dlaczego nie "dla (auto const c: s) {...}"? –

51

std::regex_token_iterator wykonuje rodzajowe tokenizacja oparciu regex. To może lub nie może być przesadą za to prosty podział na pojedynczy znak, ale działa i nie jest zbyt gadatliwy:

std::vector<std::string> split(const string& input, const string& regex) { 
    // passing -1 as the submatch index parameter performs splitting 
    std::regex re(regex); 
    std::sregex_token_iterator 
     first{input.begin(), input.end(), re, -1}, 
     last; 
    return {first, last}; 
} 
+24

Świetny pomysł, bardzo trudne do odczytania. –

+2

Należy wspomnieć, że jest to specyficzne dla MSFT. Nie istnieje w systemach POSIX. – jackyalcine

+0

Wygląda na to, że jest również dostępny w [boost.] (Http://www.boost.org/doc/libs/1_56_0/libs/regex/doc/html/boost_regex/ref/regex_token_iterator.html) – phs

4

Mój wybór jest boost::tokenizer ale nie mam żadnych ciężkich zadań i testów z ogromnym danych . Przykład z doładowania doc z modyfikacją lambda:

#include <iostream> 
#include <boost/tokenizer.hpp> 
#include <string> 
#include <vector> 

int main() 
{ 
    using namespace std; 
    using namespace boost; 

    string s = "This is, a test"; 
    vector<string> v; 
    tokenizer<> tok(s); 
    for_each (tok.begin(), tok.end(), [&v](const string & s) { v.push_back(s); }); 
    // result 4 items: 1)This 2)is 3)a 4)test 
    return 0; 
} 
+2

dlaczego nie zakres na podstawie? –

+5

W C++ 11, 'dla (auto && s: tok) {v.push_back (s); } '. –

3
#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <string> 


using namespace std; 

vector<string> split(const string& str, int delimiter(int) = ::isspace){ 
    vector<string> result; 
    auto e=str.end(); 
    auto i=str.begin(); 
    while(i!=e){ 
    i=find_if_not(i,e, delimiter); 
    if(i==e) break; 
    auto j=find_if(i,e, delimiter); 
    result.push_back(string(i,j)); 
    i=j; 
    } 
    return result; 
} 

int main(){ 
    string line; 
    getline(cin,line); 
    vector<string> result = split(line); 
    for(auto s: result){ 
    cout<<s<<endl; 
    } 
} 
+0

Dlaczego 'int' jako ogranicznik i dlaczego' int delimiter (int) '' '(int)'? – Ela782

+1

@ Ela782 to argument funkcji wskaźnik, funkcja, która akceptuje parametr int i zwraca int. Wartością domyślną jest funkcja isspace. – Fsmv

13

Oto (może mniej gadatliwy) sposób rozdzielić ciąg (w oparciu o post pan wspomniał).

#include <string> 
#include <sstream> 
#include <vector> 
std::vector<std::string> split(const std::string &s, char delim) { 
    std::stringstream ss(s); 
    std::string item; 
    std::vector<std::string> elems; 
    while (std::getline(ss, item, delim)) { 
    elems.push_back(item); 
    // elems.push_back(std::move(item)); // if C++11 (based on comment from @mchiasson) 
    } 
    return elems; 
} 
+4

Jeśli używasz C++ 11, możesz to zrobić, aby uniknąć ciągów podczas wstawiania do wektora: elems.push_back (std :: move (element)); – mchiasson

2

To jest moja odpowiedź. Pełne, czytelne i wydajne.

std::vector<std::string> tokenize(const std::string& s, char c) { 
    auto end = s.cend(); 
    auto start = end; 

    std::vector<std::string> v; 
    for(auto it = s.cbegin(); it != end; ++it) { 
     if(*it != c) { 
      if(start == end) 
       start = it; 
      continue; 
     } 
     if(start != end) { 
      v.emplace_back(start, it); 
      start = end; 
     } 
    } 
    if(start != end) 
     v.emplace_back(start, end); 
    return v; 
} 
+0

Chyba, że ​​ktoś chce używać UTF8 lub kilku znaków. – v010dya

+0

http://www.cplusplus.com/reference/cstring/strchr/ Jeśli dozwolone jest korzystanie z programu strchr, może pomóc w implementacji. – phoad

5

Poniżej przedstawiono przykład podziału ciągu znaków i wypełniania wektor z wyekstrahowanych pierwiastków za pomocą boost.

#include <boost/algorithm/string.hpp> 

std::string my_input("A,B,EE"); 
std::vector<std::string> results; 

boost::algorithm::split(results, my_input, is_any_of(",")); 

assert(results[0] == "A"); 
assert(results[1] == "B"); 
assert(results[2] == "EE"); 
1

Innym rozwiązaniem inspired by other answers regex, ale mam nadzieję, że krótsze i łatwiejsze do odczytania:

std::string s{"String to split here, and here, and here,..."}; 
std::regex regex{R"([\s,]+)"}; // split on space and comma 
std::sregex_token_iterator it{s.begin(), s.end(), regex, -1}; 
std::vector<std::string> words{it, {}}; 
1

Oto C++ 11 rozwiązanie, które wykorzystuje tylko std :: string :: find(). Separator może mieć dowolną liczbę znaków. Parsowane tokeny są wyprowadzane przez iterator wyjścia, który zwykle jest std :: back_inserter w moim kodzie.

Nie testowałem tego z UTF-8, ale oczekuję, że powinien działać tak długo, jak wejście i ogranicznik są poprawnymi ciągami UTF-8.

#include <string> 

template<class Iter> 
Iter splitStrings(const std::string &s, const std::string &delim, Iter out) 
{ 
    if (delim.empty()) { 
     *out++ = s; 
     return out; 
    } 
    size_t a = 0, b = s.find(delim); 
    for (; b != std::string::npos; 
      a = b + delim.length(), b = s.find(delim, a)) 
    { 
     *out++ = std::move(s.substr(a, b - a)); 
    } 
    *out++ = std::move(s.substr(a, s.length() - a)); 
    return out; 
} 

Niektóre przypadki testowe:

void test() 
{ 
    std::vector<std::string> out; 
    size_t counter; 

    std::cout << "Empty input:" << std::endl;   
    out.clear(); 
    splitStrings("", ",", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, empty delimiter:" << std::endl;   
    out.clear(); 
    splitStrings("Hello, world!", "", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, non-empty delimiter" 
       ", no delimiter in string:" << std::endl;   
    out.clear(); 
    splitStrings("abxycdxyxydefxya", "xyz", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, non-empty delimiter" 
       ", delimiter exists string:" << std::endl;   
    out.clear(); 
    splitStrings("abxycdxy!!xydefxya", "xy", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, non-empty delimiter" 
       ", delimiter exists string" 
       ", input contains blank token:" << std::endl;   
    out.clear(); 
    splitStrings("abxycdxyxydefxya", "xy", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, non-empty delimiter" 
       ", delimiter exists string" 
       ", nothing after last delimiter:" << std::endl;   
    out.clear(); 
    splitStrings("abxycdxyxydefxy", "xy", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 

    std::cout << "Non-empty input, non-empty delimiter" 
       ", only delimiter exists string:" << std::endl;   
    out.clear(); 
    splitStrings("xy", "xy", std::back_inserter(out)); 
    counter = 0;   
    for (auto i = out.begin(); i != out.end(); ++i, ++counter) { 
     std::cout << counter << ": " << *i << std::endl; 
    } 
} 

oczekiwany wynik:

 
Empty input: 
0: 
Non-empty input, empty delimiter: 
0: Hello, world! 
Non-empty input, non-empty delimiter, no delimiter in string: 
0: abxycdxyxydefxya 
Non-empty input, non-empty delimiter, delimiter exists string: 
0: ab 
1: cd 
2: !! 
3: def 
4: a 
Non-empty input, non-empty delimiter, delimiter exists string, input contains blank token: 
0: ab 
1: cd 
2: 
3: def 
4: a 
Non-empty input, non-empty delimiter, delimiter exists string, nothing after last delimiter: 
0: ab 
1: cd 
2: 
3: def 
4: 
Non-empty input, non-empty delimiter, only delimiter exists string: 
0: 
1: 
Powiązane problemy