Получить последнюю часть URL - PullRequest
0 голосов
/ 01 августа 2020

Как мне получить последнюю часть URL-адреса? Скажем, переменная url равна https://somewhere.com/stuff/hello. Как я получу от этого hello?

Ответы [ 2 ]

0 голосов
/ 01 августа 2020

Использование rfind и substr

Возможно, с

#include <iostream>
#include <string>

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

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

    return 0;
}

Но только если у вас есть / перед последней частью

0 голосов
/ 01 августа 2020
#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 ()

ссылки:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...