Splitting string into words length-based lists c#

后端 未结 5 1784
春和景丽
春和景丽 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 15:07

    First, let's declare a class that can hold a length as well as a list of words

    public class WordList
    {
        public int WordLength { get; set; }
        public List Words { get; set; }
    }
    

    Now, we can build a list of word lists with

    string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
    string[] words = input.Trim().Split();
    List list = words
        .GroupBy(w => w.Length)
        .OrderBy(group => group.Key)
        .Select(group => new WordList { 
            WordLength = group.Key, 
            Words = group.Distinct().OrderBy(s => s).ToList() 
        })
        .ToList();
    

    The lists are sorted by length and aphabetically respectively.


    Result

    enter image description here

    e.g.

    list[2].WordLength ==> 4
    list[2].Words[1] ==> "bbbb"
    

    UPDATE

    If you want, you can process the result immediately, instead of putting it into a data structure

    string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
    
    var query = input
        .Trim()
        .Split()
        .GroupBy(w => w.Length)
        .OrderBy(group => group.Key);
    
    // Process the result here
    foreach (var group in query) {
        // group.Key ==> length of words
        foreach (string word in group.Distinct().OrderBy(w => w)) {
           ...
        }
    }
    

提交回复
热议问题