How to get the last part of a string?
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();
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();
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();