Splitting string into words length-based lists c#

后端 未结 5 1788
春和景丽
春和景丽 2021-01-12 14:17

I have a string of words separated by spaces. How to split the string into lists of words based on the words length?

Example

inpu

5条回答
  •  盖世英雄少女心
    2021-01-12 14:57

    You can use Linq GroupBy

    edit Now I applied Linq to generate the string list you wanted for output.

    edit2 applied multiple input, single output as in edited question. It is just a Distinct call in Linq

    string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
    
    var list = input.Split(' ');
    
    var grouped = list.GroupBy(s => s.Length);
    
    foreach (var elem in grouped)
    {
        string header = "List " + elem.Key + ": ";
        // var line = elem.Aggregate((workingSentence, next) => next + ", " + workingSentence);
    
        // if you want single items, use this
        var line = elem.Distinct().Aggregate((workingSentence, next) => next + ", " + workingSentence);
        string full = header + " " + line;
        Console.WriteLine(full);
    }
    
    
    // output: please note the last blank in the input string! this generates the 0 list
    List 0:  ,
    List 2:  cc, bb, aa
    List 3:  ccc, bbb, aaa
    List 4:  cccc, bbbb, aaaa
    

提交回复
热议问题