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 failed
    return (fail() ? 0 : (void *)this);
}

我在文檔里沒有找到這個的說明, 所以最后我還是用了比較規范的方式:

std::string str = "abc def";
std::istringstream iss(str);
while (iss.good())
{
    iss >> str;
    std::cout << str << std::endl;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM