How to get the last part of a line?

Given this line:

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

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

I thought about reversing the entire line, looking for the first "/", we take everything on the left and vice versa. However, I hope there is a better / more concise method. Thoughts?

Thanks Paul

+52
c # regex
Aug 02 '10 at 11:23
source share
9 answers

single line with Linq:

 string lastPart = text.Split('/').Last(); 
+114
Aug 02 2018-10-11T00:
source share

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

When you work with a URI, I would recommend using the System.Uri class. This provides verification and secure access to any part of the URI.

 Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType"); string lastSegment = uri.Segments.Last(); 
+62
Aug 02 '10 at 12:32
source share

You can use String.LastIndexOf .

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

Another option is to use Uri if you need it. It makes sense to parse other parts of uri and work well with the query string, for example: BusinessRelationType?q=hello world

 Uri uri = new Uri(s); string leaf = uri.Segments.Last(); 
+38
Aug 2 '10 at 11:25
source share

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 since LastIndexOf returns -1 if no value is found, the second line returns the entire line if there is no / in the text.

+16
Aug 02 '10 at 11:25
source share

Here is a fairly concise way to do this:

 str.Substring(str.LastIndexOf("/")+1); 
+9
Aug 2 '10 at 11:27
source share
 if (!string.IsNullOrEmpty(url)) return url.Substring(url.LastIndexOf('/') + 1); return null; 
+3
Aug 02 '10 at 11:26
source share

A little advice for any stupid or unobserved people (or those who recently gave up coffee and are stupid, unobservable, rude ... like me). Windows file paths use '\' ... all examples here, on the other hand, use '/' .

So use '\\' to get the end of the path to the Windows file! :)

The solutions here are perfect and complete, but perhaps this could prevent some other poor soul from spending an hour, as I just did!

+2
Jan 24 '13 at 12:28
source share

Alternatively, you can use the regular expression /([^/]*?)$ To match

+1
Aug 02 '10 at
source share
 Path.GetFileName 

treats / and \ as delimiters.

 Path.GetFileName ("http://s.opencalais.com/1/pred/BusinessRelationType") = "BusinessRelationType" 
+1
Jul 08 '16 at 7:04 on
source share



All Articles