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()

猜你喜欢

转载自www.cnblogs.com/woodyzhu/p/11845580.html