0
我已經創建了將char*
拆分爲vector
的函數,但問題是運行此方法後,此vector
的所有元素都是輸入行中的最後一個元素。將輸入字符*拆分爲向量
例子:
輸入:abc def ghi
載體:ghi, ghi, ghi
vector <const char*> dane;
void split(char* str, char* sep){
char* cstr = str;//str.c_str konwersja str na char*
char* current;
current = strtok(cstr, sep);
string s;
while(current != NULL){
s = current;
int foundF = s.find_first_not_of("-.\"-\\/!,`");
int foundL = s.find_last_not_of("-.\"-\\/!,`");
if(foundL==string::npos)//find first or last zwrocilo nulla
foundL = s.length();
if(foundF==string::npos)
foundF = 0;
s = s.substr(foundF, foundL + 1);
const char* c = s.c_str();
dane.push_back(c);
current=strtok(NULL, sep);
}
}
int main(){
char* c = new char[256];
cin.getline(c,256);
cout<<c<<endl;
split(c, " ");
for(int i = 0; i < dane.size(); i++){
cout<<dane.at(i)<<endl;
}
return 0;
}
也許這個問題可以幫助你:http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c – 2013-05-11 07:46:23
可能的重複[將字符串拆分成矢量的字](http://stackoverflow.com/questions/8425214/splitting-string-into-a-vectorstring-of-words) –
user93353
2013-05-11 07:48:39
旁註:爲什麼你使用全局變量?另外,要注意const的正確性。 'void split(const char * str,const char * sep,vector&dane)''會更好,然後'dane'作爲main()的局部變量。 –
2013-05-11 07:58:47