C# 查找字符串中相邻的单词

C# 查找字符串中相邻的单词,c#,C#,我需要能够找到不同数量的单词组合,其中单词在字符串中彼此相邻 例如: 字符串:1234 我需要找到这样的组合: one two two three three four one two three two three four 根据字符串中的单词数量,组合可能会变大。 我很挣扎,因为初始字符串可以是任意数量的单词 编辑 这段代码甚至还不太接近,但我正在与它的逻辑作斗争。我下面的代码做出了我不知道的假设 string[] inputs = input.Replace("/", "").Split

我需要能够找到不同数量的单词组合,其中单词在字符串中彼此相邻

例如:

字符串:
1234

我需要找到这样的组合:

one two
two three
three four
one two three
two three four
根据字符串中的单词数量,组合可能会变大。 我很挣扎,因为初始字符串可以是任意数量的单词

编辑

这段代码甚至还不太接近,但我正在与它的逻辑作斗争。我下面的代码做出了我不知道的假设

string[] inputs = input.Replace("/", "").Split('-');
            List<string> returnList = new List<string>();
            for (int i = 0; i <= inputs.Length; i++ )
            {
                returnList.Add(inputs[i]);
                if (i > 0)
                {
                    returnList.Add(inputs[i - 1] + " " + inputs[i] + " " + inputs[i + 1]);
                }
            }
string[]inputs=input.Replace(“/”,“”)。Split(“-”);
List returnList=新列表();
对于(int i=0;i 0)
{
添加(输入[i-1]+“”+输入[i]+“”+输入[i+1]);
}
}

您可以首先调用源字符串上的String.Split函数,使用“”(或其他空格)作为分隔符。这将得到一个字符串数组,其中每个元素都是一个单词。之后,使用嵌套循环构建每个字符串,如下代码所示:

私有静态列表GetStringCombos(字符串源字符串)
{
string[]sourceArray=sourceString.Split(“”);
var newStrings=新列表();
对于(int-startIndex=0;startIndex
    static void Main(string[] args)
    {
        const string startingString = "one two three four";
        List<string> l = startingString.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList();
        var combinations = l.Select(q => FindPairs(q, l))
                   .ToList()
                   .SelectMany(r => r);
        foreach (var combination in combinations)
        {
            Console.WriteLine(String.Join(",", combination));
        }
    }
    private static List<List<string>> FindPairs(string s, List<string> list)
    {
        List<List<string> > result = new List<List<string>>();
        int index = list.IndexOf(s);
        for (int t = 2; t < list.Count; t++)
        {
            if (index + t <= list.Count)
            {
                var words = list.Skip(index).Take(t).ToList();
                if (words.Count() >= 2)
                {
                    result.Add(words);
                }
            }
        }
        return result;
    }

这与您的问题的结果相匹配。解决方案的关键是将Take和Skip运算符组合在一起。LINQ的SelectMany将列表展平为一个列表。

您可以粘贴您尝试的代码吗?这看起来像一个算法问题。您是否在问一种方法来检查特定的一组单词是否确实出现在ea旁边字符串中的ch other(这是一个简单的检查)或者你正在尝试构建一个字符串数组,其中包含源字符串中所有可能的相邻单词组合?我想听听你的第二个建议。'构建一个字符串数组,其中包含源字符串中所有可能的相邻单词组合'在这里搜索排列,你会发现排列似乎非常复杂在正确的方向上,只是我不想要从左到右的所有可能的组合,只是那些元素彼此相邻的组合。如果需要较大的组合(即长输入字符串),则应在嵌套循环中使用StringBuilder这并不能回答这个问题。若要评论或要求作者澄清,请在其帖子下方留下评论。
one,two
one,two,three
two,three
two,three,four
three,four