By PythonPython


2020-08-01 13:10:37 8 Comments

How would I get the last part of a URL? Say the variable url is https://somewhere.com/stuff/hello. How would I get hello from this?

2 comments

@MatthieuL 2020-08-01 13:15:01

#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"
    }
}

With find_last_of() and substr()

references :

@john 2020-08-01 13:17:12

szUrl and szHello? Reverse polish notation is bad enough, inappropriately applied its even worse.

@MatthieuL 2020-08-01 13:35:32

@john I modified.

@Armin Montigny 2020-08-01 13:15:20

Using rfind and substr

Maybe with

#include <iostream>
#include <string>

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

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

    return 0;
}

But only, if you have a / in front of the last part

Related Questions

Sponsored Content

59 Answered Questions

[SOLVED] How to get the value from the GET parameters?

23 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1702417 View
  • 4001 Score
  • 23 Answer
  • Tags:   git url git-remote

23 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2864114 View
  • 3046 Score
  • 23 Answer
  • Tags:   javascript url

18 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1277316 View
  • 4906 Score
  • 18 Answer
  • Tags:   http url browser

36 Answered Questions

18 Answered Questions

[SOLVED] Encode URL in JavaScript?

28 Answered Questions

[SOLVED] Get the full URL in PHP

  • 2011-07-20 21:29:51
  • DiegoP.
  • 2987517 View
  • 977 Score
  • 28 Answer
  • Tags:   php url

33 Answered Questions

[SOLVED] How do I get the current absolute URL in Ruby on Rails?

31 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1157642 View
  • 4412 Score
  • 31 Answer
  • Tags:   http url uri urn rfc3986

32 Answered Questions

[SOLVED] Get current URL with jQuery?

  • 2009-01-02 06:42:54
  • venkatachalam
  • 2176022 View
  • 1853 Score
  • 32 Answer
  • Tags:   javascript jquery url

Sponsored Content