Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create Acronym from Word

Given any string, I'd like to create an intelligent acronym that represents the string. If any of you have used JIRA, they accomplish this pretty well.

For example, given the word: Phoenix it would generate PHX or given the word Privacy Event Management it would create PEM.

I've got some code that will accomplish the latter:

 string.Join(string.Empty, model.Name
                .Where(char.IsLetter)
                .Where(char.IsUpper))

This case doesn't handle if there is only one word and its lower case either.

but it doesn't account for the first case. Any ideas? I'm using C# 4.5

like image 836
amcdnl Avatar asked Jan 07 '14 15:01

amcdnl


1 Answers

For the Phoenix => PHX, I think you'll need to check the strings against a dictionary of known abbreviations. As for the multiple word/camel-case support, regex is your friend!

var text = "A Big copy DayEnergyFree good"; // abbreviation should be "ABCDEFG"
var pattern = @"((?<=^|\s)(\w{1})|([A-Z]))";
string.Join(string.Empty, Regex.Matches(text, pattern).OfType<Match>().Select(x => x.Value.ToUpper()))

Let me explain what's happening here, starting with the regex pattern, which covers a few cases for matching substrings.

// must be directly after the beginning of the string or line "^" or a whitespace character "\s"
(?<=^|\s)
// match just one letter that is part of a word
(\w{1})
// if the previous requirements are not met
|
// match any upper-case letter
([A-Z])

The Regex.Matches method returns a MatchCollection, which is basically an ICollection so to use LINQ expressions, we call OfType() to convert the MatchCollection into an IEnumerable.

Regex.Matches(text, pattern).OfType<Match>()

Then we select only the value of the match (we don't need the other regex matching meta-data) and convert it to upper-case.

Select(x => x.Value.ToUpper())
like image 91
Justin Ryder Avatar answered Sep 21 '22 13:09

Justin Ryder