go去掉最后一个字符_CodeGo.net>如何获取字符串的最后一部分?

CodeGo.net>如何获取字符串的最后一部分?

给定此字符串:

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

我想得到它的最后一部分:“业务关系类型”

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

谢谢保罗

Paul Fryer asked 2020-01-15T06:39:45Z

11个解决方案

114 votes

Linq的单线:

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

或如果其中可能有空字符串(加上null选项):

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

naspinski answered 2020-01-15T06:40:09Z

63 votes

每当我发现自己编写诸如System.Uri之类的代码时,我就会感觉到自己可能正在做一些不安全的事情,并且可能已经有更好的方法了。

当您使用URI时,建议您使用System.Uri类。 这为您提供了验证,并且可以安全,轻松地访问URI的任何部分。

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

string lastSegment = uri.Segments.Last();

Benp44 answered 2020-01-15T06:40:33Z

38 votes

您可以使用Uri。

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();

Kobi answered 2020-01-15T06:40:58Z

16 votes

您可以使用LastIndexOf查找最后一个/,然后使用LastIndexOf查找之后的所有内容:

int index = text.LastIndexOf('/');

string rhs = text.Substring(index + 1);

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

Jon Skeet answered 2020-01-15T06:41:22Z

9 votes

这是一种非常简洁的方法:

str.Substring(str.LastIndexOf("/")+1);

Igor Zevaka answered 2020-01-15T06:41:42Z

3 votes

if (!string.IsNullOrEmpty(url))

return url.Substring(url.LastIndexOf('/') + 1);

return null;

Matthew Abbott answered 2020-01-15T06:41:58Z

2 votes

对于任何愚蠢的人或不懂事的人(或最近放弃了咖啡,而像傻子,愚蠢的人,脾气暴躁的人一样...)的小窍门-Windows文件路径使用'\\' ...另一方面,所有示例 ,请使用'/'。

因此,请使用'\\'来获取Windows文件路径的结尾! :)

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

Simon Kiely answered 2020-01-15T06:42:27Z

2 votes

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

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

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

GiampaoloGabba answered 2020-01-15T06:42:51Z

1 votes

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

DixonD answered 2020-01-15T06:43:12Z

1 votes

Path.GetFileName

将/和\视为分隔符。

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

"BusinessRelationType"

citykid answered 2020-01-15T06:43:31Z

0 votes

对于字符串:

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

CSharper answered 2020-01-15T06:44:00Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值