问题描述
我有一个字符串,例如big bad dog",我怎样才能得到一个包含所有可能的单词/短语组合的 string[] 数组?
I have a string such as "big bad dog", how can I get an string[] array which includes all the possible word/phrase combinations?
所以,我想返回big"、bad"、dog"、big bad"、bad dog"和big bad dog"——因此原始字符串中单词的顺序必须是尊重.
So, I would like to return "big", "bad", "dog", "big bad", "bad dog" and "big bad dog" - therefore the order of the words in the original string must be respected.
这可以用正则表达式来完成吗?
Is this something that could be done with a regular expression?
推荐答案
我认为这是一个递归解决的好问题.我的看法:
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")
返回您的短语列表.
A findWords("big", "bad", "dog")
returns your list of phrases.
编辑为仅包含连续短语.
Edited to only include consecutive phrases.
这篇关于c#生成单词组合数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!