2012-02-24 87 views
37

使用C++ 11拆分字符串最簡單的方法是什麼?使用C++拆分字符串11

我已經看到了這個post使用的方法,但是我覺得應該使用新標準做一個不太冗長的方法。

編輯:我想有一個vector<string>作爲結果,並能夠在一個字符上劃界。

+1

分裂的空間?我不認爲C++ 11在這裏添加了任何東西,認爲[接受的答案](http://stackoverflow.com/a/237280/845092)仍然是最好的方法。 – 2012-02-24 17:42:09

+0

分裂後你想要什麼?打印到cout?或者得到一個子串的向量? – balki 2012-02-24 17:42:37

+0

這不是正則表達式解析的用途嗎? – 2012-02-24 17:46:58

回答

4

我不知道這是不是很詳細,但它可能更容易爲動態語言,如JavaScript的經驗豐富的人。它使用的唯一C++ 11功能是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

爲什麼不'for(auto const c:s){...}'? – 2012-04-19 12:19:07

51

std::regex_token_iterator基於正則表達式執行通用標記。它可能會或可能不會矯枉過正對單個字符做簡單的拆分,但它的工作原理,是不是太冗長:

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

好主意,超級難讀。 – 2012-02-24 21:36:03

+2

應該提到這是MSFT特定的。在POSIX系統上不存在。 – jackyalcine 2014-09-06 20:11:26

+0

看起來它也可用於[boost。](http://www.boost.org/doc/libs/1_56_0/libs/regex/doc/html/boost_regex/ref/regex_token_iterator.html) – phs 2014-09-06 20:57:17

4

我的選擇是boost::tokenizer,但我沒有任何工作任務重和測試與龐大的數據。 來自實例文檔提升與拉姆達修改:

#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

爲什麼不以範圍爲基礎? – 2012-04-19 12:19:46

+5

在C++ 11中,for(auto && s:tok){v.push_back(s); }'。 – 2015-05-26 19:08:03

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

爲什麼'int'作爲分隔符,爲什麼'int delimiter(int)''(int)'? – Ela782 2017-08-22 22:22:11

+1

@ Ela782它是一個函數指針參數,一個接受一個int參數並返回int的函數。缺省值是isspace函數。 – Fsmv 2017-09-04 21:40:27

13

這裏是一個(也許更簡潔)的方式來分割字符串(根據你所提到的post)。

#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

如果你使用的是C++ 11,你也可以在插入到你的矢量時避免字符串拷貝: elems.push_back(std :: move(item)); – mchiasson 2015-02-15 16:03:07

2

這是我的答案。詳盡,可讀和高效。

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

除非有人想使用UTF8或幾個字符。 – v010dya 2016-07-08 08:31:39

+0

http://www.cplusplus.com/reference/cstring/strchr/如果允許使用strchr,它可能有助於您的實施。 – phoad 2016-10-23 03:07:52

5

下面是一個字符串分割和填充用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

另一個正則表達式的解決方案inspired by other answers但希望更短,更易於閱讀:

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

這裏是僅使用的std :: string ::找一個C++ 11溶液()。分隔符可以是任意數量的字符。解析令牌通過輸出迭代器輸出,通常是我的代碼中的std :: back_inserter。

我還沒有用UTF-8測試過,但我期望它應該工作,只要輸入和分隔符都是有效的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; 
} 

一些測試用例:

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; 
    } 
} 

預期輸出:

 
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: