两个嵌套的 for 循环将对两个单词的组合执行此操作
Dim s = "heavy duty cable reel".Split()
For i As Integer = 0 To s.Length - 2
For k As Integer = i + 1 To s.Length - 1
Console.WriteLine(s(i) + " " + s(k))
Next
Next
输出是
重负
重型电缆
沉重的卷轴
电缆
责任卷轴
电缆卷筒
更新
这是一个将所有短语长度从 2 到单词数 - 1 的版本。我为此创建了一个类。
Public Class PhraseBuilder
Private words As String()
Private phrases As List(Of String)
Public Function GetList(ByVal initialPhrase As String) As List(Of String)
words = initialPhrase.Split()
phrases = New List(Of String)()
For phraseLength As Integer = 2 To words.Length - 1
AddPhrases("", 0, phraseLength)
Next
Return phrases
End Function
Private Sub AddPhrases(ByVal phrase As String, ByVal start As Integer,
ByVal wordCount As Integer)
If wordCount >= 1 Then
For i As Integer = start To words.Length - wordCount
AddPhrases(phrase + " " + words(i), i + 1, wordCount - 1)
Next i
Else
phrases.Add(phrase.TrimStart())
End If
End Sub
End Class
你可以用
Sub PrintPhrases()
Dim phraseBuilder = New PhraseBuilder()
Dim phrases = phraseBuilder.GetList("heavy duty cable reel")
For Each phrase As String In phrases
Console.WriteLine(phrase)
Next
End Sub
结果将是
重负
重型电缆
沉重的卷轴
电缆
责任卷轴
电缆卷筒
重型电缆
重型卷轴
重型电缆卷筒
电缆卷筒
请注意,我在这里使用了递归。递归允许将 for 语句嵌套到任意深度。我没有使用 a StringBuilder
,因为我们必须创建短语开头的副本。使用自动执行此操作的字符串更容易完成,因为它们是不可变的。没有简单的方法来克隆StringBuilder
.