Search code examples
.netstringvb.netindexof

Finding locations of a char in a string


How can I get the position of certain characters in a string?

Example: my string = "hello, what you doing"

and I would like to return the position of o from those string which should return me position numbers 4, 13 & 17. I've tried str.IndexOf but it only returns the first occurrence of o.

Here is what I have tried:

    Dim str = "hello, what you doing"
    Dim dIndex = str.IndexOf("o")
    If (dIndex > -1) Then
        Console.WriteLine(dIndex.toString())
    End If

any method will do.

I am using Visual Studio 2008.


Solution

  • There is an overload of IndexOf which takes the position to start looking from.

    So once you have found the position of the first matching character, you can tell it to carry on looking starting just after that position.

    Here I made a function which returns a list of the positions. (If there are no matches then the list will be empty.)

    Option Strict On
    Option Infer On
    
    Module Module1
    
        Function IndexesOf(s As String, c As Char) As List(Of Integer)
            Dim positions As New List(Of Integer)
            Dim pos = s.IndexOf(c)
            While pos >= 0
                positions.Add(pos)
                pos = s.IndexOf(c, pos + 1)
            End While
    
            Return positions
    
        End Function
    
        Sub Main()
            Dim os = IndexesOf("hello, what you doing", "o"c)
            For Each pos In os
                Console.WriteLine(pos)
            Next
    
            Console.ReadLine()
    
        End Sub
    
    End Module
    

    Output:

    4
    13
    17