给定以下字符串:
http://s.opencalais.com/1/pred/BusinessRelationType
我想要获取它的最后一部分:"BusinessRelationType"
我一直在考虑反转整个字符串,然后查找第一个"/",取左边的所有内容并反转。但是,我希望有更好/更简洁的方法。你有什么想法吗?
谢谢,保罗
Linq的一行代码:
var lastPart = text.Split('/').Last();
如果你可能在其中有空字符串(加上 null 选项):
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,因此如果文本中没有斜杠,第二行代码将返回整个字符串。var suffix = new string(str.Reverse().TakeWhile(c => c != '.').ToArray());
。由于Reverse
是一个返回Enumerable
的“惰性”方法,我认为它应该很不错,对吗? - gdoron这里有一个相当简洁的方法来解决这个问题:
str.Substring(str.LastIndexOf("/")+1);
if (!string.IsNullOrEmpty(url))
return url.Substring(url.LastIndexOf('/') + 1);
return null;
如果URL以/结尾,接受的答案可能会产生不希望的结果(空字符串)。
为了避免这种情况,您可以使用以下方法:
string lastPart = text.TrimEnd('/').Split('/').Last();
对于一些粗心或者不太观察的人(或最近刚戒掉咖啡的像我这样的易怒、不太观察的人),这里有一个小技巧 - Windows文件路径使用反斜杠 '\'
,而所有这里的示例则使用斜杠 '/'
。
所以要使用双反斜杠 '\\'
来获取Windows文件路径的末尾!>:)
这里的解决方案完美而完整,但也许这个技巧可以避免其他可怜的人像我一样浪费一个小时的时间!
Path.GetFileName
Path.GetFileName ("http://s.opencalais.com/1/pred/BusinessRelationType") =
"BusinessRelationType"
或者您可以使用正则表达式/([^/]*?)$
来查找匹配项
http://s.opencalais.com/1/pred/BusinessRelationType/
请注意最后的斜杠,lastPart
的内容将为空。使用以下代码:string lastPart = text.Substring(0, text.LastIndexOf('/')).Split('/').Last();
将会解决这个问题 :) - L. Page