如何获得一个string的最后一部分?
给定这个string:
http://s.opencalais.com/1/pred/BusinessRelationType 我想要得到它的最后一部分:“BusinessRelationType”
我一直在考虑扭转整个string,然后寻找第一个“/”,把所有的东西都放在那个左边,然后相反。 不过,我希望有一个更好/更简洁的方法。 思考?
谢谢,保罗
与Linq单行:
 string lastPart = text.Split('/').Last(); 
 你可以使用String.LastIndexOf 。 
 int position = s.LastIndexOf('/'); if (position > -1) s = s.Substring(position + 1); 
 另一个select是使用Uri ,如果这是你所需要的。 这有利于parsinguri的其他部分,并且处理好查询string,例如: BusinessRelationType?q=hello world 
 Uri uri = new Uri(s); string leaf = uri.Segments.Last(); 
 每当我发现自己正在编写诸如LastIndexOf("/") ,我感觉我可能正在做一些不安全的事情,并且可能有更好的方法可用。 
 在使用URI时,我build议使用System.Uri类。 这为您提供validation和安全,方便地访问URI的任何部分。 
 Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType"); string lastSegment = uri.Segments.Last(); 
 您可以使用string.LastIndexOf来查找最后一个/然后是Substring来获取它后面的所有内容: 
 int index = text.LastIndexOf('/'); string rhs = text.Substring(index + 1); 
 请注意,如果未find该值,则LastIndexOf返回-1,如果文本中没有/,则第二行将返回整个string。 
这是一个非常简洁的方法来做到这一点:
 str.Substring(str.LastIndexOf("/")+1); 
 if (!string.IsNullOrEmpty(url)) return url.Substring(url.LastIndexOf('/') + 1); return null; 
 或者,您可以使用正则expression式/([^/]*?)$来查找匹配项 
 对于任何愚蠢或不相关的人(或任何最近放弃咖啡,愚蠢,不友善,不喜欢自己的人)的小技巧 –  Windows文件path使用'\' …所有的例子在这里另一方面,使用'/' 。 
 所以使用'\\'来获得Windows文件path的结尾!  🙂 
这里的解决scheme是完美的,完整的,但也许这可能会阻止一些其他可怜的灵魂浪费我一小时的时间!
 Path.GetFileName 
认为/和\为分隔符。
 Path.GetFileName ("http://s.opencalais.com/1/pred/BusinessRelationType") = "BusinessRelationType"