Alex Rivera | Logout

How to get the last part of a string?

Asked 2010-08-02T11:23:21.247
66

Given this string:

http://s.opencalais.com/1/pred/BusinessRelationType

I want to get the last part of it: "BusinessRelationType"

I have been thinking about reversing the whole string then looking for the first "/", take everything to the left of that and reverse that. However, I'm hoping there is a better/more concise method. Thoughts?

Thanks, Paul

Edit
Report

3 Answers

103

Whenever I find myself writing code such as LastIndexOf("/"), I get the feeling that I am probably doing something that's unsafe, and there is likely a better method already available.

As you are working with a URI, I would recommend using the System.Uri class. This provides you with validation and safe, easy access to any part of the URI.

Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType");
string lastSegment = uri.Segments.Last();
answered 2010-08-02T12:32:09.100
20

You can use string.LastIndexOf to find the last / and then Substring to get everything after it:

int index = text.LastIndexOf('/');
string rhs = text.Substring(index + 1);

Note that as LastIndexOf returns -1 if the value isn't found, this the second line will return the whole string if there is no / in the text.

answered 2010-08-02T11:25:32.350
3
if (!string.IsNullOrEmpty(url))
    return url.Substring(url.LastIndexOf('/') + 1);
return null;
answered 2010-08-02T11:26:21.617

Your Answer