2014-05-02 42 views
0

我需要能夠找到不同數量的單詞組合,其中單詞在字符串中彼此相鄰。查找字串相同的查詢詞

例子:

字符串:one two three four

我需要找到組合是這樣的:

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]); 
       } 
      } 
+2

你可以粘貼你試過的代碼嗎?它看起來像一個算法問題。 –

+0

您是否要求一種方法來檢查一組特定的單詞是否確實在字符串中相互緊挨着出現(這是一個簡單的檢查),還是試圖構建一個包含相鄰單詞的每種可能組合的字符串數組源字符串? – Jargon

+0

我想要你的第二個建議。 '建立一個包含源字符串中相鄰單詞的每個可能組合的字符串數組' – mdance

回答

1

這是使用一個比特LINQ的C#溶液...

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; 
    } 

它產生的結果...

one,two 
one,two,three 
two,three 
two,three,four 
three,four 

它與您的問題的結果相匹配。解決方案的關鍵是結合Take和Skip運算符。 LINQ的SelectMany將列表列表放到一個列表中。

-1

你可以通過調用源字符串的String.Split函數來開始,使用「」(或其他空格)作爲分隔符。這會得到一個字符串數組,其中每個元素都是一個單詞。在此之後,使用嵌套循環來構建每個串,如在下面的代碼:

private static List<string> GetStringCombos(string sourceString) { string[] sourceArray = sourceString.Split(' '); var newStrings = new List<string>(); for (int startIndex = 0; startIndex < sourceArray.Length; startIndex++) { for (int endIndex = startIndex; endIndex < sourceArray.Length; endIndex++) { string newString = ""; for (int currentIndex = startIndex; currentIndex <= endIndex; currentIndex++) { newString = string.Join(" ", newString, sourceArray[currentIndex]); } newStrings.Add(newString.Trim()); } } return newStrings; }

+0

如果你期望有大的組合(即一個長輸入字符串),你應該在嵌套循環中使用一個StringBuilder – Jargon

+0

這並沒有提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 –