提问者:小点点

获取URL的最后一部分


如何获取URL的最后部分? 假设变量urlhttps://somewhere.com/stuff/hello。 我如何从中获得hello


共2个答案

匿名用户

使用rfindsubstr

也许和

#include <iostream>
#include <string>

int main() {
    std::string url{"https://somewhere.com/stuff/hello"};

    std::cout << url.substr(url.rfind('/')+1);

    return 0;
}

但只有在最后一个部分前面有/的情况下

匿名用户

#include <iostream>
#include <string>
int main() {
 
    const std::string url("https://somewhere.com/stuff/hello");
    const std::size_t indexLastSeparator = url.find_last_of("/");
    if (indexLastSeparator != std::string::npos)
    {
        const std::string lastPartUrl = url.substr(indexLastSeparator+1); // +1 to not keep /
        std::cout << lastPartUrl << '\n'; // print "hello"
    }
}

使用find_last_of()和substr()

参考资料:

  • https://en.cppreference.com/W/cpp/string/basic_string/find_last_of
  • https://en.cppreference.com/W/cpp/string/basic_string/substr