2017-07-26 92 views
0

我正在嘗試編寫一個函數,它將一個字符串和一個分隔符作爲輸入並返回一個字符串數組。出於某種原因,下面的代碼運行到分段錯誤。我想知道可能是什麼問題?在C++中分割函數

char** split(string thing, char delimiter){ 

    thing+='\0';//add null to signal end of string 
    char**split_string = new char*[100]; 

    int i=0,j=0,l=0; //indexes- i is the ith letter in the string 
        // j is the jth letter in the lth string of the new array 
    int length = thing.length(); 
    while (i < length){ 
      if ((thing[i]!=delimiter && thing[i]!='\0')){ 
        split_string[l][j]=thing[i]; 
        j++; 
      } 
      else { 
        j=0; //reset j-value 
        l++; 
      } 
      i++; 
    } 

    return split_string; 

}

+2

爲什麼不將源字符串「拆分」爲字符串向量?爲什麼要使用指針和動態分配(特別是如果源字符串中沒有100個「標記」)? –

+3

'split_string [l]'是一個未初始化的指針,包含一些隨機垃圾,指向內存中的某個隨機位置。 'split_string [l] [j] = thing [i]'然後嘗試寫入該隨機存儲單元。 –

+0

您是否嘗試過使用Google錯誤消息?瞭解它究竟意味着什麼?然後,很容易找到你出錯的地方。 –

回答

0

每個char *有這樣單獨初始化。

int len = 100; 

char**split_string = new char*[len]; // len holds the number of pointers 

for(int k = 0; k < len; k++) { 
    split_string[k] = new char[500]; // holds len of string (here Max word size is considered 500) 
} 

在C++中,建議堅持的std::string使用會更減少複雜性和增加可讀性 - 。

您的代碼將失敗趕上最後一個子的保持你的while循環剛剛找到\0之前爆發的。要解決此問題,您需要將while (i < length)更改爲while (i <= length)

使用矢量<字符串>

vector<string> split(string thing, char delimiter){ 
    int len = 100; 
    vector<string> v; 
    char c[500]; 
    int i=0,j=0; 
    int length = thing.length(); 
    while (i <= length){ 
     if (thing[i] != delimiter && thing[i] != '\0') { 
      c[j]=thing[i]; 
      j++; 
     } 
     else { 
      c[j] = '\0'; 
      v.push_back(c); 
      memset(c, 0, sizeof c); 
      j = 0; 
     } 
     i++; 
    } 
    return v; 
} 

Demo

0

1)當您找到新的子字符串時,請爲每個子字符串(類似char [l] = new char [100])分配內存。

由於您不知道開始本身的子串數量,請考慮使用向量。考慮使用矢量< string> split_string。在循環中,當你找到一個新的子字符串時,你只需將該字符串推入向量中。最後,你將擁有矢量中的所有拆分字符串。

1

char**split_string = new char*[100];

後,您仍然需要初始化每個創建的100個字符*指針。

static const size_t str_len = 50; //assuming length will not exceed 
for(size_t ix = 0 ; ix < 100 ; ++ix){ 
    split_string[ix] = new char[str_len]; 
} 

你也需要確保在寫入split_string不超過所分配的內存在這種情況下,其50個你沒有splited字符串的更多然後100

1

更好拆分std::stringstd::vector<std::string>。使用以下功能

#include <sstream> 
#include <string> 
#include <vector> 

std::vector<std::string> split(std::string str, char delim) { 
    std::vector<std::string> result; 
    std::stringstream ss(str); 
    std::string token; 
    while (getline(ss, token, delim)) 
     result.push_back(token); 
    return result; 
} 
+0

我猜OP正在爲分裂函數編寫一個實現,而'getline'在內部進行所有檢查。 –