【问题标题】:How to remove sub string [duplicate]如何删除子字符串[重复]
【发布时间】:2018-04-12 07:21:27
【问题描述】:

我有一个字符串 -> 1234,2345,12341,6442

需要通过C#代码删除上面字符串中的12341,我的字符串在C#中应该是1234,2345,6442

【问题讨论】:

  • 查找字符串替换。
  • 这里的规则是什么?为什么要删除12341?请分享不适合您的代码。

标签: c# string substring substr


【解决方案1】:

您可以使用简单的字符串替换来做到这一点:

namespace ReplaceExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("1234,2345,12341,6442".Replace("12341,", string.Empty));
        }
    }
}

考虑到要替换的数字可能是逗号不应该包含替换模式的最后一个元素,因此使用正则表达式可能是一个更优雅的解决方案:

using System.Text.RegularExpressions;    

namespace ReplaceExample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(Regex.Replace("1234,2345,12341,6442", @"12341[,]*", string.Empty));
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 1970-01-01
    • 2018-02-20
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多