【问题标题】:Split string into multiple strings with specific criteria将字符串拆分为具有特定条件的多个字符串
【发布时间】:2018-01-06 03:51:47
【问题描述】:

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

  • 必须至少包含 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);
    }
}

它输出以下内容:

hello how 
hello how are 
hello how are you 

我也想找其他人,需要一点帮助。

【问题讨论】:

    标签: c# string split


    【解决方案1】:

    一种方法是遍历每个单词并获取其所有可能的序列。

    例子:

    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 
    

    【讨论】:

    • 你打败了我!
    • 这正是我想要的。感谢您的帮助,不胜感激。
    【解决方案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
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多