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

后端 未结 6 1440
傲寒
傲寒 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: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()
        );
    

提交回复
热议问题