Splitting string into words length-based lists c#

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

    A bit lengthy solution but does get the result in a Dictionary

    class Program
        {
            public static void Main()
            {
                Print();
                Console.ReadKey();
            }
    
            private static void Print()
            {
                GetListOfWordsByLength();
    
                foreach (var list in WordSortedDictionary)
                {
                    list.Value.ForEach(i => { Console.Write(i + ","); });
                    Console.WriteLine();
                }
            }
    
            private static void GetListOfWordsByLength()
            {
                string input = " aa aaa aaaa bb bbb bbbb cc ccc cccc ";
    
                string[] inputSplitted = input.Split(' ');
    
                inputSplitted.ToList().ForEach(AddToList);
            }
    
            static readonly SortedDictionary> WordSortedDictionary = new SortedDictionary>();
    
            private static void AddToList(string s)
            {
                if (s.Length > 0)
                {
                    if (WordSortedDictionary.ContainsKey(s.Length))
                    {
                        List list = WordSortedDictionary[s.Length];
                        list.Add(s);
                    }
                    else
                    {
                        WordSortedDictionary.Add(s.Length, new List {s});
                    }
                }
            }
        }
    

提交回复
热议问题