std::string的split函数
生活随笔
收集整理的這篇文章主要介紹了
std::string的split函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
剛剛要找個按空格分離std::string的函數, 結果發現了stackoverflow上的這個問題.
也沒仔細看, 直接拿來一試, 靠, 不對啊, 怎么分離后多出個空字符串, 也就是 "abc def" 分離后, 得到的是:
?? "abc"
?? "def"
?? ""
這不科學! 老外在耍我么, 再看原來的回答下面已經有人commet了:
while (iss) { string subs; iss >> subs; cout << "Substring: " << sub << endl; }滿心歡喜的再一試, 靠, 還是不對啊! 老外也太不靠譜了, 再看下面的comment, 樂了:
@Eduardo: that's wrong too... you need to test iss between trying to stream another value and using that value,?i.e. string sub; while (iss >> sub) cout << "Substring: " << sub << '\n'; – Tony D Apr 11 '12 at 2:24
感覺老外有時候也是會激動, 手抖的, 哈哈.
拿這位仁兄的代碼再試, OK了.
?
不過這些老外的代碼感覺還是不太規范的, 比如在判斷iss是否可用的時候, 是直接判斷的, 跟進去的話, 可以看到這里其實是調用了這么個函數:
__CLR_OR_THIS_CALL operator void *() const {// test if any stream operation has failedreturn (fail() ? 0 : (void *)this); }我在文檔里沒有找到這個的說明, 所以最后我還是用了比較規范的方式:
std::string str = "abc def"; std::istringstream iss(str); while (iss.good()) {iss >> str;std::cout << str << std::endl; }?
?
轉載于:https://www.cnblogs.com/chaoswong/p/3457849.html
總結
以上是生活随笔為你收集整理的std::string的split函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 系统登录异常
- 下一篇: Zend Studio 高亮显示dwt和