2013-03-31 13 views
0

我對C++來說很新,我想我在這段代碼的某個地方犯了一個小錯誤。到目前爲止我沒有發現它。我希望你能幫助我,告訴我他/她/爲什麼是錯的? 非常感謝提前。C++在字符上正確地分割文本

的代碼:

std::vector<std::string> spliter(const std::string& s, char delimiter) 
{ 
     std::vector<std::string> result; 

     size_t start = 0; 
     for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start)) 
     { 
      result.push_back(s.substr(start,i-start)); 
      start = i+1; 
     } 
     iprintf("\x1b[2J"); 
     printf("\x1b[4;0HDone Splitting Text."); 
     swiWaitForVBlank(); 
     return result; 
} 

參數給出: s = "$ 00-000 SS ''Prologue'' CF N00-001 V 1 MP 20" 定界符= ' '(空格)

預期結果:

result[0] = $ 
result[1] = 00-000 
result[2] = SS 
etc. 

當前錯誤的結果:

result[0] = 
result[1] = 
result[2] = 00-000 
etc. 

任何幫助,非常感謝!

+0

你能看到第一次在你的循環中,你推回's.substr(0,0)'? –

+0

等一下,'i'在第一次循環發生之前沒有設置?儘管如此,它並沒有解釋缺失的'$'字符。 – Smileynator

+0

你見過[this](http://stackoverflow.com/a/236803/701092)問題的答案嗎?你的代碼看起來有點類似。 – 0x499602D2

回答

1

這裏是修復你的算法可能的方式:

#include <vector> 
#include <string> 

std::vector<std::string> spliter(const std::string& s, char delimiter) 
{ 
    std::vector<std::string> result; 

    std::string::size_type start = 0; 
    auto pos = s.find(delimiter, 0); 
    while (pos != std::string::npos) 
    { 
     result.push_back(s.substr(start, pos - start)); 
     start = pos + 1; 
     pos = s.find(delimiter, start); 
    } 

    if (start < s.length()) 
    { 
     result.push_back(s.substr(start)); 
    } 

    return result; 
} 

這裏是這個算法給您的測試字符串正確輸出的live example

請注意,你可以概括這只是通過改變splitter的第二個參數的類型(和傳球" "代替' ',當然)用字符串作爲分隔符,而不是單個字符的工作。

+0

這個完美的作品!由於我的編譯器工作原理,我必須將'auto'更改爲'std :: size_t',但這太棒了!我會花一些時間來分析德魯和Vidit告訴我的錯誤。再次感謝! – Smileynator

+0

@Smileynator:好的,很高興幫助。另外,如果你不/不能使用'auto',那麼使用的確切類型應該是'std :: string :: size_type'。大多數情況下,這隻會和'std :: size_t'一樣,但爲了保持安全,請使用'std :: string :: size_type'。 –

+0

我注意到,'size_t'似乎也起作用!我發現這種方式也更容易閱讀。下次我不會使用這樣的for循環。這隻會造成混亂。 – Smileynator

2

我相信這個問題是在循環。你從0開始,而你推的第一件事就是從0到0

size_t start = 0; 
    for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start)) 
    { 
     result.push_back(s.substr(start,i-start)); 
     start = i+1; 
    } 

,而不是如果你從s.find(delimiter, start)它應該工作開始iExample here..