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

64

给定以下字符串:

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

我想要获取它的最后一部分:"BusinessRelationType"

我一直在考虑反转整个字符串,然后查找第一个"/",取左边的所有内容并反转。但是,我希望有更好/更简洁的方法。你有什么想法吗?

谢谢,保罗

12个回答

0

关于字符串:

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

-1

也许你可以尝试做:

string x = "http://s.opencalais.com/1/pred/BusinessRelationType"
string.IsNullOrWhiteSpace(x)?x.Split('/').Last(): x,

请通过确保代码在最左边的行缩进了4个空格或在粘贴后按下ctrl+k进行标记来添加代码格式。您经常需要手动缩进第一行,有时甚至需要重复此过程,但目前它违反了指南,因为它将代码倾泻在文本中。 - T. Nielsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接