簡體   English   中英

C ++中的分割功能

[英]Splitting function in 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;

}

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

您仍然需要初始化創建的100個char *指針。

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,並且拆分的字符串不會超過100。

最好將std::string拆分為std::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;
}

每個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 ,以減少復雜性並提高可讀性。

您的代碼將無法抓住最后一個子字符串,因為您在找到\\0之前就退出了while循環 要解決此問題,您需要將while (i < length)更改為while (i <= length)

使用vector <string>

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

演示

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

由於您不知道開頭本身的子字符串數,請考慮使用向量。 考慮使用vector <string> split_string。 在循環中,無論何時找到新的子字符串,都只需將該字符串推入向量中即可。 最后,您將在向量中包含所有分割的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM