gpt4 book ai didi

c++ - 使用/分隔符获取给定字符串的最后一个目录的文本

转载 作者:行者123 更新时间:2023-11-28 06:37:21 25 4
gpt4 key购买 nike

给定一个 URL(字符串),如下所示:

www.testsite.com/pictures/banners/whatever/

我希望能够获取 URL 中最后一个目录的字符(在本例中是“随便”,我还想删除正斜杠)。执行此操作的最有效方法是什么?

感谢您的帮助

最佳答案

#include <iostream>
#include <string>

std::string getlastcomponent(std::string s) {
if (s.size() > 0 && s[s.size()-1] == '/')
s.resize(s.size() - 1);
size_t i = s.find_last_of('/');
return (i != s.npos) ? s.substr(i+1) : s;
}

int main() {
std::string s1 = "www.testsite.com/pictures/banners/whatever/";
std::string s2 = "www.testsite.com/pictures/banners/whatever";
std::string s3 = "whatever/";
std::string s4 = "whatever";
std::cout << getlastcomponent(s1) << '\n';
std::cout << getlastcomponent(s2) << '\n';
std::cout << getlastcomponent(s3) << '\n';
std::cout << getlastcomponent(s4) << '\n';
return 0;
}

关于c++ - 使用/分隔符获取给定字符串的最后一个目录的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com