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

gaf*_*afs 3 c# string split

我想根据以下条件将字符串拆分为多个字符串:

  • 它必须至少2个单词在一起
  • 每个单词必须彼此相邻

例如:"你好,你好吗"我想分成:

  • "你好,你好吗"
  • "你好"
  • "你好"
  • "如何"
  • "你好吗"
  • "你是"

不能重复多次.

到目前为止我得到的是:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它输出以下内容:

hello how 
hello how are 
hello how are you 
Run Code Online (Sandbox Code Playgroud)

我也希望得到其他人,并需要一些帮助.

Mt.*_*ers 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 
Run Code Online (Sandbox Code Playgroud)