Scott
Scott

Reputation: 6251

For each loop string

I'm getting a file content from my website:

    Dim client As WebClient = New WebClient()
    Dim text = client.DownloadString("http://myurl.com/raw.php")

The text is following:

Line
Another Line
Test1
Test2

Now, how can I run a loop through the text variable, to have a text from each line ?

I have tried this:

    Dim str As String() = text.Split(":::")
    For Each line As String In str
        MsgBox(line)
    Next

And I was finishing each line with the :::, but this method seems ugly and I hope there are better solutions?

Upvotes: 1

Views: 7060

Answers (4)

Jordi Selva Serrano
Jordi Selva Serrano

Reputation: 1

Sorry to bring this up years later... I just found a easier way to do it:

dim lin() as string
lin() = TextBox1.Text.Split(vbCrLf)

Upvotes: -1

Heinzi
Heinzi

Reputation: 172220

Using text.Split(CChar(Environment.NewLine)), as suggested in another answer, is not optimal: Environment.NewLine returns the two-character sequence CR LF on Windows systems. Thus, CChar(Environment.NewLine) returns just CR, the first character of the string. If the source of the data is from a unix system, it is likely separated by LFs.

If you are unsure about the exact line endings, you could use the following:

Dim lines As String() = text.Split(new String() {vbCrLf, vbCr, vbLf}, 
                                   StringSplitOptions.None)

That should cover all cases, since it splits on CR alone, on LF alone and on a combination of both.

Upvotes: 1

bendataclear
bendataclear

Reputation: 3850

An example of the vb.net side if useing XML:

Dim doc As New System.Xml.XmlDocument
doc.Load("http://myurl.com/raw.php")

Dim list = doc.GetElementsByTagName("article")

For Each item As System.Xml.XmlElement In list
    MsgBox(item.InnerText)
Next

Edit:

Example XML schema:

<?xml version='1.0'?>
<!-- File generated at 22/11/2012 17:22 -->
<articleList>
  <article>Hello</article>
  <article>World</article>
  <article>Fish</article>
</articleList>

Another advantage of switching to XML now will mean it will be easier to add more details in the future (like article header, date/time, auther etc).

Upvotes: 2

Dennis Traub
Dennis Traub

Reputation: 51634

Dim lines As String() = text.Split(Environment.NewLine)
For Each line As String In lines
    MsgBox(line)
Next

This maybe doesn't work because the newline character in the original string is different from Environment.Newline. This can happen if the string comes from a Unix-based source.

An alternative approach could be:

Dim reader = new StringReader(text)
While True
    Dim line = reader.ReadLine()
    If line is Nothing
        Exit While
    Else
        MsgBox(line)
    End If
End While

Upvotes: 6

Related Questions