c++中substr()/find_last_of()的應用


背景代碼:

std::string topic = topic_name.substr(topic_name.find_last_of('/') + 1); // topic_name中沒有'/',這個長度

涉及:

1、find_last_of();

解析:從string末端開始尋找子串或者字符,如果找到返回字串首字符的索引(其實就是字符中的第幾位),如果沒有匹配則返回 std::string::npos(實際上為 -1)

 
size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
size_t find_last_of (const char* s, size_t pos = npos) const;
size_t find_last_of (const char* s, size_t pos, size_t n) const;
size_t find_last_of (char c, size_t pos = npos) const noexcept;

 

 



版權聲明:本文為CSDN博主「NearXDU」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/zhangxiao93/article/details/54381613
 

2、substr();

0. 用途:一種構造string的方法

1. 兩個參數:s.substr(pos, n) ---》使用如 string str_tmp = s.substr(pos, );

通俗解釋:在s中從第pos個字符開始截取n個字符到str_tmp中;

2.一個參數:s.substr(pos)   ----》使用如:string str_tmp = s.substr(pos);

通俗解釋:在s中從第pos個字符開始截取往后字符到str_tmp中;

3. 補充:若pos的值超過了string的大小,則substr函數會拋出一個out_of_range異常;若pos+n的值超過了string的大小,則substr會調整n的值,只拷貝到string的末尾

擴展:find(),find_first_of()


免責聲明!

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



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