【问题标题】:how to remove all text after the last recurrence of a certain character如何在某个字符的最后一次重复后删除所有文本
【发布时间】:2011-05-30 21:55:00
【问题描述】:

给定任何字符串,我想删除特定字符之后的任何字母。

此字符可能在字符串中多次出现,我只想将其应用于最后一次出现。

所以让我们说“/”是字符,这里有一些例子:

http://www.ibm.com/test ==> http://www.ibm.com
你好/测试 ==> 你好

【问题讨论】:

    标签: c# string parsing


    【解决方案1】:
    if (text.Contains('/'))
        text = text.Substring(0, text.LastIndexOf('/'));
    

    var pos = text.LastIndexOf('/');
    if (pos >= 0)
        text = text.Substring(0, pos);
    

    (编辑以涵盖字符串中不存在'/'的情况,如cmets中所述)

    【讨论】:

    • ... 假设字符串中存在“/”。否则你会得到一个ArgumentOutOfRangeException
    • 为了性能,您可以运行 LastIndexOf,并检查结果是否为 -1 以检查字符串是否包含该字符。这样你只搜索字符串,而不是两次 (Contains+LastIndexOf),这对于大字符串来说可能会很昂贵。
    【解决方案2】:

    另一种选择是使用String.Remove

     modifiedText = text.Remove(text.LastIndexOf(separator));
    

    通过一些错误检查,可以将代码提取到扩展方法中,例如:

    public static class StringExtensions
    {
        public static string RemoveTextAfterLastChar(this string text, char c)
        {
            int lastIndexOfSeparator;
    
            if (!String.IsNullOrEmpty(text) && 
                ((lastIndexOfSeparator = text.LastIndexOf(c))  > -1))
            {
    
                return text.Remove(lastIndexOfSeparator);
            }
            else
            {
                return text;
            }
        }
     }
    

    可以这样使用:

    private static void Main(string[] args)
    {
        List<string> inputValues = new List<string>
        {
            @"http://www.ibm.com/test",
            "hello/test",
            "//",
            "SomethingElseWithoutDelimiter",
            null,
            "     ", //spaces
        };
    
        foreach (var str in inputValues)
        {
            Console.WriteLine("\"{0}\" ==> \"{1}\"", str, str.RemoveTextAfterLastChar('/'));
        }
    }
    

    输出:

    "http://www.ibm.com/test" ==> "http://www.ibm.com"
    "hello/test" ==> "hello"
    "//" ==> "/"
    "SomethingElseWithoutDelimiter" ==> "SomethingElseWithoutDelimiter"
    "" ==> ""
    "     " ==> "     "
    

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2014-09-08
      • 2017-04-12
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多