-1

我的网站上有一个文本文件,我通过 webclient.downloadstring 下载了整个字符串。

文本文件包含以下内容:

饼干,菜肴,糖果,(新行)返回,转发,刷新,(新行)邮件,媒体,静音,

这只是一个示例,它不是实际的 string ,但它可以用于帮助目的。

我想要的是我想下载整个字符串,找到包含用户在 a 中输入的单词的行,textbox将该行变成一个字符串,然后我想使用 string.split 作为分隔符“, " 并将字符串中的每个单词输出到richtextbox.

现在这是我使用的代码(出于隐私原因删除了一些字段)。

If TextBox1.TextLength > 0 Then
        words = web.DownloadString("webadress here")
        If words.Contains(TextBox1.Text) Then
            'retrieval code here
            Dim length As Integer = TextBox1.TextLength
            Dim word As String
            word = words.Substring(length + 1) // the plus 1 is for the ","
            Dim cred() As String
            cred = word.Split(",")
            RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
        Else
            MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
        End If
    Else
        MsgBox("Please fill in an word", MsgBoxStyle.Critical)
    End If

现在它可以工作并且没有错误,但它只适用于第 1 行,而不适用于第 2 行或第 3 行

我究竟做错了什么 ?

4

2 回答 2

0

Smi 的回答是正确的,但是由于您使用的是 VB,因此您需要在 vbNewLine 上进行拆分。\n 和 \r 用于 C#。我经常被它绊倒。

另一种方法是使用正则表达式。正则表达式匹配既可以找到您想要的单词,也可以在一个步骤中返回包含它的行。

下面是几乎没有测试过的样品。我不太清楚您的代码是否按照您所说的做,所以我根据您的描述即兴创作。

Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click

        Dim downloadedString As String
        downloadedString = "cookies,dishes,candy," _
             & vbNewLine & "back,forward,refresh," _
             & vbNewLine & "mail,media,mute,"

        'Use the regular expression anchor characters (^$) to match a line that contains the given text.
        Dim wordToFind As String = TextBox1.Text & ","  'Include the comma that comes after each word to avoid partial matches.
        Dim pattern As String = "^.*" & wordToFind & ".*$"
        Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)

        Dim M As Match = rx.Match(downloadedString)
        'M will either be Match.Empty (no matching word was found), 
        'or it will be the matching line.

        If M IsNot Match.Empty Then
            Dim words() As String = M.Value.Split(","c)
            RichTextBox1.Clear()
            For Each word As String In words
                If Not String.IsNullOrEmpty(word) Then
                    RichTextBox1.AppendText(word & vbNewLine)
                End If
            Next
        Else
            RichTextBox1.Text = "No match found."
        End If

    End Sub

End Class
于 2012-06-05T20:44:32.543 回答
0

这是因为字符串words还包含您似乎在代码中省略的换行符。您应该首先words使用分隔符\n(或\r\n,取决于平台)进行拆分,如下所示:

Dim lines() As String = words.Split("\n")

之后,你有一个字符串数组,每个元素代表一行。像这样循环它:

For Each line As String In lines
    If line.Contains(TextBox1.Text) Then
        'retrieval code here
    End If
Next
于 2012-06-03T15:42:31.610 回答