将字符串按特定条件拆分为多个字符串

3
我希望根据以下条件将字符串拆分为多个字符串:
  • 必须是至少两个单词在一起
  • 每个单词必须紧挨着
例如: "hello how are you" 我想要拆分成以下几个字符串:
  • "hello how are you"
  • "hello how are"
  • "hello how"
  • "how are"
  • "how are you"
  • "are you"
不能重复多次。
我目前的代码如下:
string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();

string temp = String.Empty;

for (int i = 0; i < words.Count; i++)
{
    temp += words[i] + " ";
    if (i > 0)
    {
        inputs.Add(temp);
    }
}

它输出如下内容:
hello how 
hello how are 
hello how are you 

我希望能得到其他人的帮助,并且需要一点协助。

2个回答

5
一种方法是对每个单词进行迭代,获取其所有可能的序列。
例如:
string input = "hello how are you";
List<string> words = input.Split(' ').ToList();
List<string> inputs = new List<string>();

for (int i = 0; i < words.Count; i++)
{
    var temp = words[i];
    for(int j = i+1;j < words.Count;j++) {
        temp += " " + words[j];
        inputs.Add(temp);
    }
}
//hello how 
//hello how are 
//hello how are you 
//how are 
//how are you 
//are you 

你比我先做到了这件事! - Magnetron
这正是我正在寻找的。感谢您的帮助,非常感激。 - gafs

2
这是伪代码:
for (int i = 0; i < words.Count - 1; i++)
{
    for each (int j = i + 1; j < words.Count; j++)
    {
        //rebuild string from words[i] through words[j] and add to list
    }
}

这个想法是将除了最后一个单词以外的每个单词都视为起始单词(因为它后面不能有单词)。对于起始单词,考虑每个可能的结束单词(第一个单词将是列表中的下一个单词,最后一个单词将是最后一个单词)。然后对于每个起始/结束单词对,重新构建字符串并添加到列表中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接