查找字符串VB的子字符串

时间:2013-04-10 16:40:36

标签: vb.net

1.以下程序将获得用户的两个输入,即A&乙
2.比从B中查找子字符串 3.最后打印结果。

虽然我的代码是

    Dim a As String
    Dim b As String
    a = InputBox("Enter First String", a)
    b = InputBox("Enter 2nd String", b)
        Dim i As Integer
        Dim j As Integer = 0
        Dim k As Integer = 0
        Dim substr As Integer = 0
        For i = 0 To a.Length - 1

            If a(i) = b(j) Then
                j += 1

                If b(j) = 0 Then
                MsgBox("second string is substring of first one")
                    substr = 1
                    Exit For
                End If
            End If
        Next i
        For i = 0 To b.Length - 1
            If b(i) = a(k) Then
                k += 1
                If a(k) = 0 Then
                MsgBox(" first string  is substring of second string")
                    substr = 1
                    Exit For
                End If
            End If
        Next i
        If substr = 0 Then
        MsgBox("no substring present")
        End If
End Sub

编译时会出现以下调试错误。

                                           Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17  24  
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27  24  

1 个答案:

答案 0 :(得分:0)

正是由于这些原因:

If b(j) = 0 Then

If a(k) = 0 Then

由于a(k)b(j)都是Char数据类型(将字符串视为字符数组),但您尝试将它们与int(0)进行比较。

如果您正在寻找一个子字符串并且您正在使用VB.NET,您可以尝试使用IndexOf方法,这是一个非常天真的例子:

If a.IndexOf(b) > -1 Then
    MsgBox("b is a substring of a")
ElseIf b.IndexOf(a) > -1 Then
    MsgBox("a is a substring of b")     
Else
    MsgBox("No substring found")
End

如果你正在使用VBA,你也可以使用InStr但我认为这个字符串是1索引而不是0索引(因为它们在VB.NET中)所以你的检查可能看起来像:

If InStr(a,b) > 0 Then
    MsgBox("b is a substring of a")
ElseIf InStr(b,a) > 0 Then
    MsgBox("a is a substring of b")     
Else
    MsgBox("No substring found")
End