简体   繁体   中英

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

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();

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();

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.

这是一个非常简洁的方法来做到这一点:

str.Substring(str.LastIndexOf("/")+1);
if (!string.IsNullOrEmpty(url))
    return url.Substring(url.LastIndexOf('/') + 1);
return null;

A small tip for any silly or unobservant people (or anyone who has recently given up coffee and is silly, unobservant, grouchy...like myself) - Windows file paths use a '\\' ...all of the examples here on the other hand, use a '/' .

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

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

The accepted answer might give undesidered results (empty string) if the url ends with /

To prevent this you can use:

string lastPart = text.TrimEnd('/').Split('/').Last();

或者,您可以使用正则表达式/([^/]*?)$来查找匹配项

Path.GetFileName

considers / and \\ as separators.

Path.GetFileName ("http://s.opencalais.com/1/pred/BusinessRelationType") =
"BusinessRelationType"

For String:

var stringUrl = "http://s.opencalais.com/1/pred/BusinessRelationType";
var lastPartOfUrl = stringUrl.Substring(stringUrl.LastIndexOf("/") + 1);

If you convert string to Uri: // Totally depends on your requirement.

var stringUrl = "http://s.opencalais.com/1/pred/BusinessRelationType";
var convertStringToUri = new Uri(stringUrl);
var lastPartOfUrl = convertStringToUri.PathAndQuery.Substring(convertStringToUri.AbsolutePath.LastIndexOf("/") + 1);

Output:

BusinessRelationType

You can also do

string x = "http://s.opencalais.com/1/pred/BusinessRelationType" string.IsNullOrWhiteSpace(x)?x.Split('/').Last(): x,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM