Get acronym from string in C # using LINQ?

Here's how I write a function to make a Java-style acronym:

string makeAcronym(string str) { string result = ""; for (int i = 0; i < str.Length; i++) { if (i == 0 && str[i].ToString() != " ") { result += str[i]; continue; } if (str[i - 1].ToString() == " " && str[i].ToString() != " ") { result += str[i]; } } return result; } 

Is there a more elegant way to do this using LINQ or using the built-in C # function?

+7
string c # linq
source share
6 answers

Here are a couple of options

Only .NET 4 using string.Join:

  string acronym = string.Join(string.Empty, input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(s => s[0]) ); 

In .NET 3.5 (or 4.0) you can:

  string acronym = new string(input.Split(new[] {' '}, stringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray()); 

Another option (my personal choice) based on your original logic:

  string acronym = new string( input.Where( (c,i) => c != ' ' && (i == 0 || input[i-1] == ' ') ) .ToArray() ); 
+13
source share

Here is a technique that I have not yet seen. It depends on the assumption that all letters that should be in the abbreviation (and only those letters) are in upper case in a string.

 string MakeAcronym(string input) { var chars = input.Where(Char.IsUpper).ToArray(); return new String(chars); } // MakeAcronym("Transmission Control Protocol") == "TCP" 
+8
source share

You can do this pretty well using the Regex / Linq command:

 String .Join("", Regex .Matches("this is a test",@"(?<=^| )\w") .Cast<Match>() .Select(m=>m.Value) .ToArray() ) 
+4
source share

You can use the LINQ Aggregate method to do this in a rather elegant way.

Something like that:

 private static string MakeAcronym2(string str) { return str.Split(' ').Aggregate("", (x, y) => x += y[0]); } 
+4
source share

LINQ may work for this, but usually I would be better off creating string values ​​using an instance of StringBuilder . This avoids unnecessary string distributions.

 string makeAcronym(string str) { var builder = new StringBuilder(); for ( var i = 0; i < str.Length; i++ ) { var c = str[i]; if ( c == ' ' ) { continue; } if ( i == 0 || str[i-1] == ' ' ) { builder.Append(c); } } return builder.ToString(); } 
+2
source share
 string makeAcronym(string str) { return new string(str.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray()); } 
0
source share

All Articles