Splitting string into words length-based lists c#

后端 未结 5 1750
春和景丽
春和景丽 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:02

    You can use Where to find elements that match a predicate (in this case, having the correct length):

    string[] words = input.Split();
    
    List twos = words.Where(s => s.Length == 2).ToList();
    List threes = words.Where(s => s.Length == 3).ToList();
    List fours = words.Where(s => s.Length == 4).ToList();
    

    Alternatively you could use GroupBy to find all the groups at once:

    var groups = words.GroupBy(s => s.Length);
    

    You can also use ToLookup so that you can easily index to find all the words of a specific length:

    var lookup = words.ToLookup(s => s.Length);
    foreach (var word in lookup[3])
    {
        Console.WriteLine(word);
    }
    

    Result:

    aaa
    bbb
    ccc
    

    See it working online: ideone


    In your update it looks like you want to remove the empty strings and duplicated words. You can do the former by using StringSplitOptions.RemoveEmptyEntries and the latter by using Distinct.

    var words = input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
                     .Distinct();
    var lookup = words.ToLookup(s => s.Length);
    

    Output:

    aa, bb, cc
    aaa, bbb, ccc
    aaaa, bbbb, cccc
    

    See it working online: ideone

提交回复
热议问题