How to get the last part of a string?
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
Solution 1:
one-liner with Linq:
var lastPart = text.Split('/').Last();
or if you might have empty strings in there (plus null option):
var lastPart = text.Split('/').Where(x => !string.IsNullOrWhiteSpace(x)).LastOrDefault();
Solution 2:
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();
Solution 3:
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();