简体   繁体   中英

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

How do I find the uppercase letters of an existing string and add (-) before each of them?

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

This code finds the uppercase letters and prints them on the screen, but I want it to print:
fhk-SG-Jndj-Hkjsd-A

How can I achieve this?

I think that using a RegEx would be much easier:

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

Another option using Linq's aggregate:

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);

Using Where Filters a sequence of values based on a predicate and then String.Concat will concatenate all the values giving you SGJHA .

Instead, you could use Select , check per character for an uppercase char and return the char prepended with a - or the same char as a string when not an uppercase char.

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# demo


To also find unicode uppercase characters using a regex, you could use \p{Lu} to find an uppercase letter that has a lowercase variant as Char.IsUpper checks for a Unicode character.

In the replacement, you can use the full match using $0 prepended with a -

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

Output

fhk-S-G-Jndj-Hkjsd-A

C# demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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