【问题标题】:All elements before last comma in a string in c#c#中字符串中最后一个逗号之前的所有元素
【发布时间】:2011-07-11 05:18:32
【问题描述】:

如何在 c# 中获取字符串中逗号(,)之前的所有元素? 例如 如果我的字符串是说

string s = "a,b,c,d";

然后我想要 d 之前的所有元素,即在最后一个逗号之前。所以我的新字符串喊看起来像

string new_string = "a,b,c";

我尝试过拆分,但我一次只能使用一个特定元素。

【问题讨论】:

    标签: c# string split


    【解决方案1】:
    string new_string = s.Remove(s.LastIndexOf(','));
    

    【讨论】:

    • 请注意,当原始字符串不包含逗号时,这将引发ArgumentOutOfRangeException 异常!所以一定要检查最后一个索引是否不是-1,或者如果你想保留一个逗号,它是否大于0。
    【解决方案2】:

    如果您想要在 last 出现之前的所有内容,请使用:

    int lastIndex = input.LastIndexOf(',');
    if (lastIndex == -1)
    {
        // Handle case with no commas
    }
    else
    {
        string beforeLastIndex = input.Substring(0, lastIndex);
        ...
    }
    

    【讨论】:

      【解决方案3】:

      使用以下正则表达式:"(.*),"

      Regex rgx = new Regex("(.*),");
      string s = "a,b,c,d";
      
      Console.WriteLine(rgx.Match(s).Groups[1].Value);
      

      【讨论】:

        【解决方案4】:

        你也可以试试:

        string s = "a,b,c,d";
        string[] strArr = s.Split(',');
        
        Array.Resize(strArr, Math.Max(strArr.Length - 1, 1))
        
        string truncatedS = string.join(",", strArr);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-23
          • 1970-01-01
          • 2012-12-25
          • 1970-01-01
          • 2020-02-05
          • 1970-01-01
          • 1970-01-01
          • 2012-12-03
          相关资源
          最近更新 更多