代码之家  ›  专栏  ›  技术社区  ›  Paul Fryer

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

  •  50
  • Paul Fryer  · 技术社区  · 15 年前

    给定此字符串:

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

    我想知道最后一部分:“BusinessRelationType”

    我一直在考虑将整个字符串反转,然后寻找第一个“/”,把所有东西都移到左边,然后反转它。不过,我希望有一个更好/更简洁的方法。思想?

    谢谢,保罗

    11 回复  |  直到 7 年前
        1
  •  111
  •   naspinski    15 年前

    一个带LINQ的衬里:

    string lastPart = text.Split('/').Last();
    
        2
  •  54
  •   Benp44    8 年前

    每当我发现自己在写代码,比如 LastIndexOf("/") 我觉得我可能在做一些不安全的事情,而且可能已经有了更好的方法。

    当您使用一个URI时,我建议您使用 System.Uri 班级。这为您提供了对URI任何部分的验证和安全、方便的访问。

    Uri uri = new Uri("http://s.opencalais.com/1/pred/BusinessRelationType");
    string lastSegment = uri.Segments.Last();
    
        3
  •  38
  •   Kobi    15 年前

    你可以使用 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();
    
        4
  •  15
  •   Jon Skeet    15 年前

    你可以使用 string.LastIndexOf 找到最后一个/然后 Substring 要得到它之后的一切:

    int index = text.LastIndexOf('/');
    string rhs = text.Substring(index + 1);
    

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

        5
  •  9
  •   Igor Zevaka    15 年前

    下面是一个非常简洁的方法:

    str.Substring(str.LastIndexOf("/")+1);
    
        6
  •  3
  •   Matthew Abbott    15 年前
    if (!string.IsNullOrEmpty(url))
        return url.Substring(url.LastIndexOf('/') + 1);
    return null;
    
        7
  •  2
  •   Simon Kiely    12 年前

    对于任何愚蠢或不注意的人(或任何最近放弃咖啡的人,愚蠢、不注意的人,易怒……像我一样)来说,这是一个小提示-Windows文件路径使用 '\' …另一方面,这里的所有示例都使用 '/' .

    所以使用一个 '\\' 获取Windows文件路径的结尾!:)

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

        8
  •  2
  •   GiampaoloGabba    7 年前

    如果URL以/

    要防止出现这种情况,您可以使用:

    string lastPart = text.TrimEnd('/').Split('/').Last();
    
        9
  •  1
  •   DixonD    15 年前

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

        10
  •  1
  •   citykid    9 年前
    Path.GetFileName
    

    将/和\视为分隔符。

    Path.GetFileName ("http://s.opencalais.com/1/pred/BusinessRelationType") =
    "BusinessRelationType"
    
        11
  •  0
  •   GThree    7 年前

    字符串:

    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