Get an acronym from a string in C# using LINQ?

后端 未结 6 1439
傲寒
傲寒 2021-01-18 01:09

Here is how I would write a function to make an acronym in Java style:

    string makeAcronym(string str)
    {
        string result = \"\";
        for (in         


        
相关标签:
6条回答
  • 2021-01-18 01:24

    LINQ can work for this but generally I find it's better to build up string values using StringBuilder instance. This allows you to avoid unnecessary string allocations.

    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();
    }
    
    0 讨论(0)
  • 2021-01-18 01:27

    Here are a couple of options

    A .NET 4 only option 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 do:

     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()
        );
    
    0 讨论(0)
  • 2021-01-18 01:32

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

    Something like this:

    private static string MakeAcronym2(string str)
    {
        return str.Split(' ').Aggregate("", (x, y) => x += y[0]);
    }
    
    0 讨论(0)
  • 2021-01-18 01:40

    Here's a technique I haven't seen so far. It depends on the assumption that all the letters that should be in the acronym (and only those letters) are in upper-case in the string.

    string MakeAcronym(string input)
    {
        var chars = input.Where(Char.IsUpper).ToArray();
        return new String(chars);
    }
    
    // MakeAcronym("Transmission Control Protocol") == "TCP"
    
    0 讨论(0)
  • 2021-01-18 01:44

    You can do this quite nicely using a Regex/Linq combo:

    String
        .Join("",
            Regex
                .Matches("this is a test",@"(?<=^| )\w")
                .Cast<Match>()
                .Select(m=>m.Value)
                .ToArray()
        )
    
    0 讨论(0)
  • 2021-01-18 01:47
    string makeAcronym(string str)
    {
        return new string(str.Split(new [] {' '}, 
            StringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray());
    }
    
    0 讨论(0)
提交回复
热议问题