鉴于此字符串:
http://s.opencalais.com/1/pred/BusinessRelationType
Run Code Online (Sandbox Code Playgroud)
我想得到它的最后一部分:"BusinessRelationType"
我一直在考虑反转整个字符串,然后寻找第一个"/",把所有内容都放在左边,然后反过来.但是,我希望有更好/更简洁的方法.思考?
谢谢,保罗
nas*_*ski 114
Linq单线:
var lastPart = text.Split('/').Last();
Run Code Online (Sandbox Code Playgroud)
Ben*_*p44 65
每当我发现自己编写代码时LastIndexOf("/"),我感觉我可能正在做一些不安全的事情,并且可能有更好的方法.
在使用URI时,我建议使用System.Uri该类.这为您提供验证并安全,轻松地访问URI的任何部分.
Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType");
string lastSegment = uri.Segments.Last();
Run Code Online (Sandbox Code Playgroud)
Kob*_*obi 38
你可以用String.LastIndexOf.
int position = s.LastIndexOf('/');
if (position > -1)
s = s.Substring(position + 1);
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用a Uri,如果你需要的话.这有利于解析uri的其他部分,并处理好查询字符串,例如:BusinessRelationType?q=hello world
Uri uri = new Uri(s);
string leaf = uri.Segments.Last();
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 16
您可以使用它string.LastIndexOf来查找最后一个/然后Substring获取它之后的所有内容:
int index = text.LastIndexOf('/');
string rhs = text.Substring(index + 1);
Run Code Online (Sandbox Code Playgroud)
请注意,LastIndexOf如果未找到值,则返回-1,如果文本中没有/,则第二行将返回整个字符串.