1

I have some Urls string, such as:

http://www.testproject.com/tokyo/4
http://www.testproject.com/india/11
http://www.testproject.com/singapore/819

How to get the number ("4". "11", "819") in the end of Url?

5 Answers 5

12

The other answers using string methods would be correct if this was a simple string, but since this is a URL, you should use the proper class to handle URIs:

var url = new Uri("http://www.testproject.com/tokyo/4");
var lastSegment = url.Segments.Last();
Sign up to request clarification or add additional context in comments.

6 Comments

That's very true, nice one :)
Can you list any corner case which this solution would handle correctly and AD.Net's answer would not? If there's no such case, his method would execute faster, no?
@dotNet If performance was the only issue, then yes the LastIndexOf would be 'faster'. But what if the URL contained a query or fragment? Or what if the desired segment wasn't always last but second from last? Using the proper parser enables a lot more flexibility.
@dotNet and AndrewHanlon the downside of your perfect answer is that the programmer is reduced to a typist with an extensive memory of MSDN reference material, whereas the string manipulation methods actually protect the programmer from one day becoming obsolete. Your perfect answer only needs speech recognition software to make the programmer unemployed. Think about that when you rush to high level functions. That day is steadily approaching. (;-D)
@dotNet ever wonder why German automobile engineers don't make their designs as simple as possible? it's called self-preservation!
|
3

Without using regex, you can find the index of last "/" by using string.LastIndexOf('/') and get the rest by using string.SubString

Comments

2

Example of what AD.Net meant:

public string getLastBit(string s) {
    int pos = s.LastIndexOf('/') + 1;
    return s.Substring(pos, s.Length - pos);
}

Returns:

4, 11, 819

When passed in an individual url.

Comments

0
string myUrl = "http://www.testproject.com/tokyo/4";

string[] parts = myUrl.Split('/');

string itIsFour = parts[parts.Length-1];

Comments

0
int LastFwdSlash = URLString.LastIndexOf('/');
String Number = URLString.Substring(LastFwdSlash + 1, URLString.Length);
int Number = int.Parse(URLString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.