Generate word combination array in c#

前端 未结 3 648
闹比i
闹比i 2021-01-13 06:37

I have a string such as \"big bad dog\", how can I get an string[] array which includes all the possible word/phrase combinations?

So, I would like to return \"big\"

3条回答
  •  无人及你
    2021-01-13 07:37

    I think this is a nice problem to solve recursively. My take:

    public static String[] findWords(params string[] args)
    {
    
            if (args.Count() == 0)
            {
                return new String[] { "" };
            }
            else
            {
                String[] oldWords = findWords(args.Skip(1).ToArray());
                String[] newWords = oldWords.Where(word => word == "" || word.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0] == args[1])
                                            .Select(word => (args[0] + " " + word).Trim()).ToArray();
    
                return oldWords.Union(newWords).ToArray();
            }
    } 
    

    A findWords("big", "bad", "dog") returns your list of phrases.

    Edit: Edited to only include consecutive phrases.

提交回复
热议问题