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

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

提交回复
热议问题