Re: [問題] strtok的問題

看板C_and_CPP作者 ( )時間15年前 (2009/05/14 12:53), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串6/7 (看更多)
※ 引述《arenda ( )》之銘言: : strok應該是要用split功能吧 : 我有一個方法,不過是C++的,應該還不錯用,參考一下:) : #include <sstream> : #include <string> : #include <iostream> : //sMyString 為要分割的字串 : std::istringstream iss(sMyString); : //分割字元 : std::string sDelim(" "); : while( iss >> sDelim ) : { : //把分割的字元輸出 : std::cout << sDelim << std::endl; : } 感謝L大指教,不過我用下列這個split函式 "偶而"會出現std::bad::alloc()錯誤 ,有人知道為什麼嗎? 謝謝 std::vector<string> Split(const std::string &src, std::string delimit, std::string null_subst) { if( src.empty() || delimit.empty() ) throw "split:empty string\0"; std::vector<string> v; std::basic_string<char>::size_type deli_len = delimit.size(); unsigned long index = std::string::npos, last_search_position = 0; while((index = src.find(delimit, last_search_position)) != std::string::npos) { if(index == last_search_position) { v.push_back(null_subst); } else { v.push_back(src.substr(last_search_position, index-last_search_position)); last_search_position = index + deli_len; } } string last_one = src.substr(last_search_position); v.push_back( last_one.empty()? null_subst:last_one ); return v; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.118.126.167

05/14 15:34, , 1F
Split("1","1","infinite loop :)");
05/14 15:34, 1F

05/15 12:47, , 2F
哈~感謝 寫到沒注意這個bug 我改一下
05/15 12:47, 2F
文章代碼(AID): #1A2wFc1K (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1A2wFc1K (C_and_CPP)