简体   繁体   English

如何获取字符串的最后一部分?

[英]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"我想得到它的最后一部分:“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:与 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.每当我发现自己在编写诸如LastIndexOf("/") ,我就会觉得我可能正在做一些不安全的事情,并且可能已经有更好的方法可用。

As you are working with a URI, I would recommend using the System.Uri class.当您使用 URI 时,我建议使用System.Uri类。 This provides you with validation and safe, easy access to any part of the URI.这为您提供了对 URI 任何部分的验证和安全、轻松的访问。

Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType");
string lastSegment = uri.Segments.Last();

You can use String.LastIndexOf .您可以使用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.如果您需要,另一种选择是使用Uri This has a benefit of parsing other parts of the uri, and dealing well with the query string, eg: BusinessRelationType?q=hello world这有利于解析 uri 的其他部分,并能很好地处理查询字符串,例如: 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:您可以使用string.LastIndexOf找到最后一个 / 然后使用Substring来获取它之后的所有内容:

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.请注意,如果未找到值,则LastIndexOf返回 -1,如果文本中没有 /,则第二行将返回整个字符串。

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

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 '/' .给任何愚蠢或不细心的人(或任何最近戒掉咖啡并且像我一样愚蠢、不细心、脾气暴躁的人)的小提示 - Windows 文件路径使用'\\' ...所有示例另一方面,使用'/'

So use a '\\\\' to get the end of a Windows file path!所以使用'\\\\'来获得 Windows 文件路径的结尾! :) :)

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 /如果 url 以 / 结尾,则接受的答案可能会给出不需要的结果(空字符串)

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.如果您将字符串转换为 Uri: // 完全取决于您的要求。

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, string x = "http://s.opencalais.com/1/pred/BusinessRelationType" string.IsNullOrWhiteSpace(x)?x.Split('/').Last(): x,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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