Strings.InStr 和 Strings.InStrRev 产生不同的结果
Strings.InStr and Strings.InStrRev producing different results
使用 Visual Studio 2019
和 Visual Basic
。下面的测试程序产生了一个我无法解释的结果。使用 InStr
的正向搜索正确找到 a case-insensitive CompareMethod.Text
的“joe”。但是反向搜索 InStrRev
没有找到“joe”...为什么?
Dim msg As String = "According to Joe, this is a beautiful day. Joe rides a bicycle!"
Dim joe As String = "Joe"
Dim joeLower As String = "joe"
Console.WriteLine(InStr(msg, joe)) ' 14 => found, expected
Console.WriteLine(InStr(msg, joeLower)) ' 0 => not found, expected
Console.WriteLine(InStr(msg, joeLower, CompareMethod.Text)) ' 14 => found, expected
Console.WriteLine(InStrRev(msg, joe)) ' 44 => found, expected
Console.WriteLine(InStrRev(msg, joeLower)) ' 0 => not found, expected
Console.WriteLine(InStrRev(msg, joeLower, CompareMethod.Text)) ' 0 => not found, why?
因为您将 CompareMethod.Text 值作为第三个参数传递,而不是搜索应开始的索引值。默认应为 -1(或从字符串末尾算起)
Console.WriteLine(InStrRev(msg, joeLower, -1, CompareMethod.Text)) ' => 44
InStrRev 中的最后两个参数都是可选的,并且因为 CompareMethod.Text 等于整数 1,所以搜索从索引 1 开始,到零只检查一个字符,当然,没有匹配找到了。
使用 Visual Studio 2019
和 Visual Basic
。下面的测试程序产生了一个我无法解释的结果。使用 InStr
的正向搜索正确找到 a case-insensitive CompareMethod.Text
的“joe”。但是反向搜索 InStrRev
没有找到“joe”...为什么?
Dim msg As String = "According to Joe, this is a beautiful day. Joe rides a bicycle!"
Dim joe As String = "Joe"
Dim joeLower As String = "joe"
Console.WriteLine(InStr(msg, joe)) ' 14 => found, expected
Console.WriteLine(InStr(msg, joeLower)) ' 0 => not found, expected
Console.WriteLine(InStr(msg, joeLower, CompareMethod.Text)) ' 14 => found, expected
Console.WriteLine(InStrRev(msg, joe)) ' 44 => found, expected
Console.WriteLine(InStrRev(msg, joeLower)) ' 0 => not found, expected
Console.WriteLine(InStrRev(msg, joeLower, CompareMethod.Text)) ' 0 => not found, why?
因为您将 CompareMethod.Text 值作为第三个参数传递,而不是搜索应开始的索引值。默认应为 -1(或从字符串末尾算起)
Console.WriteLine(InStrRev(msg, joeLower, -1, CompareMethod.Text)) ' => 44
InStrRev 中的最后两个参数都是可选的,并且因为 CompareMethod.Text 等于整数 1,所以搜索从索引 1 开始,到零只检查一个字符,当然,没有匹配找到了。