繁体   English   中英

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

[英]How to get the last part of a string?

给定这个字符串:

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

我想得到它的最后一部分:“BusinessRelationType”

我一直在考虑反转整个字符串,然后寻找第一个“/”,将所有内容放在左侧并反转。 但是,我希望有更好/更简洁的方法。 想法?

谢谢,保罗

与 Linq 的单线:

var lastPart = text.Split('/').Last();

或者如果你可能有空字符串(加上空选项):

var lastPart = text.Split('/').Where(x => !string.IsNullOrWhiteSpace(x)).LastOrDefault();

每当我发现自己在编写诸如LastIndexOf("/") ,我就会觉得我可能正在做一些不安全的事情,并且可能已经有更好的方法可用。

当您使用 URI 时,我建议使用System.Uri类。 这为您提供了对 URI 任何部分的验证和安全、轻松的访问。

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

您可以使用String.LastIndexOf

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

如果您需要,另一种选择是使用Uri 这有利于解析 uri 的其他部分,并能很好地处理查询字符串,例如: BusinessRelationType?q=hello world

Uri uri = new Uri(s);
string leaf = uri.Segments.Last();

您可以使用string.LastIndexOf找到最后一个 / 然后使用Substring来获取它之后的所有内容:

int index = text.LastIndexOf('/');
string rhs = text.Substring(index + 1);

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

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

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

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

所以使用'\\\\'来获得 Windows 文件路径的结尾! :)

这里的解决方案是完美和完整的,但也许这可以防止其他一些可怜的人像我刚才那样浪费一个小时!

如果 url 以 / 结尾,则接受的答案可能会给出不需要的结果(空字符串)

为了防止这种情况,您可以使用:

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

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

Path.GetFileName

将 / 和 \\ 视为分隔符。

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

对于字符串:

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

如果您将字符串转换为 Uri: // 完全取决于您的要求。

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

输出:

BusinessRelationType

你也可以做

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