vb.net - 字符串中区分大小写/不敏感的搜索文本

时间:2010-09-08 10:36:37

标签: vb.net

我一直在使用text.indexof()来查看字符串是否位于另一个字符串中,但是是否可以执行区分大小写/不敏感的搜索选项?我一直在寻找谷歌并没有太多运气。

如果可以计算字符串中出现的次数,那将是一个巨大的奖励!

1 个答案:

答案 0 :(得分:6)

IndexOf有几个带有StringComparison参数的重载,允许您指定各种区域性和区分大小写的选项。

例如:

Dim idx As Integer = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase)

至于计数事件,没有内置任何东西,但是自己做这件事非常简单:

Dim haystack As String = "The quick brown fox jumps over the lazy dog"
Dim needle As String = "th"
Dim comparison As StringComparison = StringComparison.OrdinalIgnoreCase

Dim count As Integer = CountOccurrences(haystack, needle, comparison)

' ...

Function CountOccurrences(ByVal haystack As String, ByVal needle As String, _
                          ByVal comparison As StringComparison) As Integer
    Dim count As Integer = 0
    Dim index As Integer = haystack.IndexOf(needle, comparison)
    While index >= 0
        count += 1
        index = haystack.IndexOf(needle, index + needle.Length, comparison)
    End While

    Return count
End Function