Is there a better way to create acronym from upper letters in C#?

梦想的初衷 提交于 2019-12-01 18:12:58

问题


What is the best way to create acronym from upper letters in C#?

Example:

Alfa_BetaGameDelta_Epsilon

Expected result:

ABGDE

My solution works, but it's not nice

        var classNameAbbreviationRegex = new Regex("[A-Z]+", RegexOptions.Compiled);
        var matches = classNameAbbreviationRegex.Matches(enumTypeName);
        var letters = new string[matches.Count];

        for (var i = 0; i < matches.Count; i++)
        {
            letters[i] = matches[i].Value;
        }

        var abbreviation = string.Join(string.Empty, letters);

回答1:


string.Join("", s.Where(char.IsUpper));



回答2:


string.Join("", s.Where(x => char.IsUpper(x))



回答3:


string test = "Alfa_BetaGameDelta_Epsilon";
string result = string.Concat(test.Where(char.IsUpper));



回答4:


You can use the Where method to filter out the upper case characters, and the Char.IsUpper method can be used as a delegate directly without a lambda expression. You can create the resulting string from an array of characters:

string abbreviation = new String(enumTypeName.Where(Char.IsUpper).ToArray());



回答5:


By using MORE regexes :-)

var ac = string.Join(string.Empty, 
                     Regex.Match("Alfa_BetaGameDelta_Epsilon", 
                                 "(?:([A-Z]+)(?:[^A-Z]*))*")
                          .Groups[1]
                          .Captures
                          .Cast<Capture>()
                          .Select(p => p.Value));

More regexes are always the solution, expecially with LINQ! :-)

The regex puts all the [A-Z] in capture group 1 (because all the other () are non-capturing group (?:)) and "skips" all the non [A-Z] ([^A-Z]) by putting them in a non-capturing group. This is done 0-infinite times by the last *. Then a little LINQ to select the value of each capture .Select(p => p.Value) and the string.Join to join them.

Note that this isn't Unicode friendly... ÀÈÌÒÙ will be ignored. A better regex would use @"(?:(\p{Lu}+)(?:[^\p{Lu}]*))*" where \p{Lu} is the Unicode category UppercaseLetter.

(yes, this is useless... The other methods that use LINQ + IsUpper are better :-) but the whole example was built just to show the problems of Regexes with Unicode)

MUCH EASIER:

var ac = Regex.Replace("Alfa_BetaGameDelta_Epsilon", @"[^\p{Lu}]", string.Empty);

simply remove all the non-uppercase letters :-)




回答6:


var str = "Alfa_BetaGammaDelta_Epsilon";
var abbreviation = string.Join(string.Empty, str.Where(c => c.IsUpper()));


来源:https://stackoverflow.com/questions/18125738/is-there-a-better-way-to-create-acronym-from-upper-letters-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!