开发者

text split problem

I have a program which scans trough a textbox1 text and displays all words from textbox1 which are more than n letters long in textbox2. Here's the complete code:

Private Function filterWords(ByVal minLenght As Short, ByVal input As String) As List(Of String)
        Dim strInput() As String = input.Split(" ")
        Dim strList As New List(Of String)
        strList = strInput.ToList()

        For Each word In strInput
      开发者_Go百科      If word.Length < minLenght Then
                strList.Remove(word)
            End If
        Next
        Return strList
    End Function

    Private Sub textbox1_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textbox1.TextChanged
        textbox2.Text = ""
        Dim strOut As New List(Of String)

        strOut = filterWords(4, textbox1.Text)

        For Each w In strOut
            textbox2.Text += w & " "
        Next
    End Sub

If you for example type a b c d then it will not show anything in textbox2, but if you type a then press enter and then b, it will show both of them. What should I write to avoid this?


That really depends on how you define a word. Your current implementation defines that a space donates the end of a word. You define this by only passing the space to input.Split. If you also want to define that a period (.) ends a word, add it: input.Split(" .").
If you want to make a word end on a new line, add it: input.Split(" ." & Environment.NewLine.ToString()).

An alternative approach would be to use regular expressions, maybe like so:

Private Function filterWords(ByVal minLength As Short, ByVal input As String) _
    As List(Of String)

    Dim strList As New List(Of String)
    Dim wordMatches = Regex.Matches(input, "\w+").Cast(Of Match)
    For Each wordMatch In wordMatches
        If wordMatch.Value.Length >= minLength Then
            strList.Add(wordMatch.Value)
        End If
    Next
    Return strList

End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜