2017-09-08 34 views
-1

我試圖製作將字符串分割成二維數組的程序token[100][100]。它會將整個字符串拆分爲單獨的單詞,但每當它遇到一段時間時,它應該是token[i++][j]。到目前爲止,我有這個。從字符中分割字符串

#include <iostream> 
#include <istream> 
#include <string> 
#include <sstream> 
#include <vector> 
#include <algorithm> 
using namespace std; 
int main() 
{ 
    string code; 
    getline(cin, code); 
    string codef[100]; 
    string token[100][100]; 
    int j = 0, i=0; 
    for (i = 0; i < 2; i++) { 
     stringstream ssin(code); 
     while (ssin.good() && j < 4) { 
      ssin >> token[i][j]; 
      ++j; 
      if (token[i][j] == ".") { 
       break; 
      } 
     } 
    } 

    for (i = 0; i < 4; i++) { 
     for (j = 0; j < 4; j++) { 
      cout << token[i][j] << endl; 
     } 
     cout << endl; 
    } 
    return 0; 
} 

我做的方式,它需要你的時期,因爲之前把一個空間,它會檢查不同的字符串,如果你一堆期間,像這樣:「你好。」它不會明顯地認出它。我不希望發生這種情況,是否有更好的方法來完成這項工作?現在我把字符串限定爲每句只有2個句子和4個詞,包括在技術上只有3個詞,然後是句號。

回答

1

爲什麼不簡單地使用std::string::find_first_of來搜索簡單的香草std :: string上的分隔符?如果沒有發現,它將返回std::string::npos。順便說一句:我真的會建議放棄舊的數組爲std :: array或std :: vector。使用std :: vector會讓你擺脫那些糟糕的硬編碼限制。

無論如何,這是我的建議。注意:我忽略了對數組訪問的限制檢查,以使代碼更易於閱讀,無論是遷移到向量並使用push_back,還是您必須添加限制檢查

我覺得代碼幾乎不言自明,只有一句話:if(pos > last_pos)是需要的,因爲pos == last_pos,當我們沒有找到另一個分隔符。

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string code = "The quick brown fox jumps over the lazy dog. Lorem ipsum dolor. Cooky"; 

    std::string token[100][100]; 
    std::size_t last_pos = 0, pos; 
    int sentence = 0, word = 0; 
    while ((pos = code.find_first_of(". ", last_pos)) != std::string::npos) 
    { 
     if (pos > last_pos) 
      token[sentence][word] = code.substr(last_pos, pos-last_pos /*length*/); 

     if(code.substr(pos, 1)[0] == '.') 
     { 
      ++sentence; 
      word = 0; 
     } 
     else 
      ++word; 
     last_pos = pos+1; 
    } 
    if (last_pos < code.length()) 
     token[sentence][word] = code.substr(last_pos, std::string::npos); 


    for (int i = 0; i < 4; i++) { 
     for (int j = 0; j < 4; j++) { 
      std::cout << token[i][j] << std::endl; 
     } 
     std::cout << std::endl; 
    } 

    return 0; 
} 

輸出有點模糊,因爲你的硬編碼的限制,但沒有任何與字符串分割,所以我離開它,因爲它是:

The 
quick 
brown 
fox 


Lorem 
ipsum 
dolor 


Cooky