小编jus*_*ing的帖子

C#在字符串中的每个数字序列后添加逗号

我有很多数字字符串.我需要重新格式化字符串以在所有数字序列后添加逗号.数字有时可能包含其他字符,包括12-3或12/4,例如

  • "你好1234再见"应该是" 你好1234,再见 "
  • "987中间文本654"应为" 987,中间文本654 ",
  • "1/2是包含其他字符的数字"应为" 1/2,是包含其他字符的数字 "
  • "这也12-3有数字"应该是" 这也是12-3,有数字 "

谢谢你们

编辑: 我的例子没有考虑任何特殊字符.我最初没有把它包括在内,因为我认为如果有人能更有效地做到这一点,我会得到一个全新的视角 - 我的坏!

    private static string CommaAfterNumbers(string input)
    {
        string output = null;

        string[] splitBySpace = Regex.Split(input, " ");
        foreach (string value in splitBySpace)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (int.TryParse(value, out int parsed))
                {
                    output += $"{parsed},";
                }
                else
                {
                    output += $"{value} ";
                }
            }
        }
        return output;
    }
Run Code Online (Sandbox Code Playgroud)

c# string

5
推荐指数
1
解决办法
110
查看次数

标签 统计

c# ×1

string ×1