简体   繁体   中英

How to find all substring instances?

I have a program which will locate a substring by index. For instance, searching for "no" in "Yes no yes no" would return 4 , the character index of the first "no".

I would like it to identify multiple occurrences. For instance, the above example would return both 4 and 11 (index of the other occurrence).

IndexOf has a set of overloads that can be used for this.

    Dim str = "Yes No Yes No"
    str.IndexOf("No", 6)

This starts searching from character 6. However I'd be tempted to use a regular expression instead.

    Dim regex As New System.Text.RegularExpressions.Regex("No")
    For Each match As RegularExpressions.Match In regex.Matches(str)
        Console.WriteLine("Match found @ {0}", match.Index)
    Next

This will give you much more control of the matching if you need to extend your rules further and IMO provides a clearer interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM