• 0

[vb.net] string question


Question

hi,

normally using a string.indexof("something") gives the first found results but how can you get the second or third indexof of the same searched string?

ok, i suck at explaining things, letme take it to the example:

i have a string like this:

#text part1#description#web link#

when i do string.IndexOf("#") i get 0 which is the first one but how can i get the second index for that character? i mean the one between the fisrt part and description or the one between description and web link?

thank you.

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

I understand what you are trying to do, and here is a solution. The String.IndexOf() function can accept a search character but can also accept a starting location.

So, the following code will loop through a string and find all instances of a character within a string.

       Dim stringToSearch As String = "#text1 part1#description#web link#"
        Dim searchSequence As Char = "#"

        Dim lastIndexFound As Integer = -1
        Do
            lastIndexFound = stringToSearch.IndexOf(searchSequence, lastIndexFound + 1)
            If (lastIndexFound <> -1) Then MessageBox.Show(lastIndexFound.ToString())
        Loop While lastIndexFound <> -1

But, you can also break a string into segments based on a character. So you could have .Net fill a string array with the contents "", "text1 part2", "description", "web link","" and then just ignore the blank text results.

       ' Using A Better Approach
        Dim parsedString() As String
        Dim stringContents As String
        parsedString = stringToSearch.Split("#")
        For Each stringContents In parsedString
            If (stringContents <> "") Then MessageBox.Show(stringContents)
        Next

Link to comment
Share on other sites

  • 0

i never thought arrays can be implemented into this one :)

it looks like its much more convenient to use the second method instead of the first one, thanks for pointing that out..

Cheers!

Link to comment
Share on other sites

  • 0

Are you kidding? Arrays are used and useful for ANYTHING, especially any sort of looping or iteration. In fact, anybody that "hard codes" a loop should be smacked ;)

Link to comment
Share on other sites

  • 0
Are you kidding?  Arrays are used and useful for ANYTHING, especially any sort of looping or iteration.  In fact, anybody that "hard codes" a loop should be smacked ;)

584828396[/snapback]

i am learning.. slowly slowly :D

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.