C#如何在字符串中的每个大写字符前添加连字符

问题描述

如何找到现有字符串的大写字母并在每个字母前添加 (-)?

string inputStr = "fhkSGJndjHkjsdA";
string outputStr = String.Concat(inputStr.Where(x => Char.IsUpper(x)));
Console.WriteLine(outputStr);
Console.ReadKey();

代码找到大写字母并将它们打印在屏幕上,但我希望它打印:
fhk-S-G-Jndj-Hkjsd-A

我怎样才能做到这一点?

解决方法

我认为使用 RegEx 会容易得多:

string outputStr = Regex.Replace(inputStr,"([A-Z])","-$1");
,

另一个使用 Linq 聚合的选项:

string inputStr = "fhkSGJndjHkjsdA";
var result = inputStr.Aggregate(new StringBuilder(),(acc,symbol) =>
    {
        if (Char.IsUpper(symbol))
        {
            acc.Append('-');
            acc.Append(symbol);
        }
        else
        {
            acc.Append(symbol);
        }
        return acc;
    }).ToString();

Console.WriteLine(result);
,

使用 Where 根据谓词过滤一系列值,然后 String.Concat 将连接所有为您提供 SGJHA 的值。 >

相反,您可以使用 Select,检查每个字符是否为大写字符,并返回前面带有 - 的字符或与字符串相同的字符(如果不是大写字符)。

string inputStr = "fhkSGJndjHkjsdA";
String outputStr = String.Concat(inputStr.Select(c => Char.IsUpper(c) ? "-" + c : c.ToString()));
Console.WriteLine(outputStr);

输出

fhk-S-G-Jndj-Hkjsd-A

C# demo


要使用正则表达式查找 unicode 大写字符,您可以使用 \p{Lu} 查找具有小写变体的大写字母,因为 Char.IsUpper 检查 Unicode 字符。

在替换中,您可以使用带有 $0 前缀的 - 的完整匹配

string inputStr = "fhkSGJndjHkjsdA";
string outputStr = Regex.Replace(inputStr,@"\p{Lu}","-$0");
Console.WriteLine(outputStr);

输出

fhk-S-G-Jndj-Hkjsd-A

C# demo