tags:

views:

240

answers:

7

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

+21  A: 

You can use String.LastIndexOf.

int position = s.LastIndexOf('/');
if (position > -1)
    s = s.Substring(position + 1);

Another option is to use a Uri, if that's what you need. This has a benefit of parsing other parts of the uri, and dealing well with the query string, eg: BusinessRelationType?q=hello world

Uri uri = new Uri(s);
string leaf = uri.Segments.Last();
Kobi
+1 for mentioning `Uri`.
Oded
+11  A: 

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.

Jon Skeet
+3  A: 
if (!string.IsNullOrEmpty(url))
    return url.Substring(url.LastIndexOf('/') + 1);
return null;
Matthew Abbott
+6  A: 

Here is a pretty concise way to do this:

str.Substring(str.LastIndexOf("/")+1);
Igor Zevaka
+1  A: 

Alternatively you can use regular expression /([^/]*?)$ to find match

DixonD
Laziness doesn't work barwards, but you don't need it here anyway. `[^/]*$` will do.
Kobi
+9  A: 

one-liner with Linq:

string lastPart = text.Split('/').Last();
naspinski
@naspinski Cool
Paul Fryer
For the record, `text.Split('/').Last()` also works, if you're looking for short `:)`
Kobi
@Kobi - good call, I will update the solution!
naspinski
+5  A: 

Whenever I find myself writing code such as LastIndexOf("/"), I get a bad feeling that I am writing code that firstly might be unsafe, and secondly has probably already been written for me.

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();
Benp44
+1 Better to use the Uri class to parse Uris
gt