繁体   English   中英

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

[英]C# How to add a hyphen before each uppercase character in a string

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

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

此代码找到大写字母并将它们打印在屏幕上,但我希望它打印:
fhk-SG-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);

Output

fhk-S-G-Jndj-Hkjsd-A

C# 演示


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

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

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

Output

fhk-S-G-Jndj-Hkjsd-A

C# 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM