2

嗨,我有一个函数可以找到两个字符串之间最长的公共子字符串。它工作得很好,只是当它到达任何单引号时它似乎会中断:'

这导致它有时无法真正找到最长的子字符串。

谁能帮我调整这个函数,使它在子字符串中包含单引号?我知道它需要在某个我不确定的地方逃脱。

示例:字符串 1:您好,这是杰夫的狗。字符串 2:您好,这是杰夫的狗。

运行该函数后,最长的公共子字符串将是:您好,这是 jeff

编辑:似乎也发生在“-”上。

它不会将单引号后的任何内容作为子字符串的一部分计算在内。这是功能:

Public Shared Function LongestCommonSubstring(str1 As String, str2 As String, ByRef subStr As String)
    Try
        subStr = String.Empty

        If String.IsNullOrEmpty(str1) OrElse String.IsNullOrEmpty(str2) Then
            Return 0
        End If

        Dim num As Integer(,) = New Integer(str1.Length - 1, str2.Length - 1) {}
        Dim maxlen As Integer = 0
        Dim lastSubsBegin As Integer = 0
        Dim subStrBuilder As New StringBuilder()

        For i As Integer = 0 To str1.Length - 1
            For j As Integer = 0 To str2.Length - 1
                If str1(i) <> str2(j) Then
                    num(i, j) = 0
                Else
                    If (i = 0) OrElse (j = 0) Then
                        num(i, j) = 1
                    Else
                        num(i, j) = 1 + num(i - 1, j - 1)
                    End If

                    If num(i, j) > maxlen Then
                        maxlen = num(i, j)

                        Dim thisSubsBegin As Integer = i - num(i, j) + 1

                        If lastSubsBegin = thisSubsBegin Then
                            subStrBuilder.Append(str1(i))
                        Else
                            lastSubsBegin = thisSubsBegin
                            subStrBuilder.Length = 0
                            subStrBuilder.Append(str1.Substring(lastSubsBegin, (i + 1) - lastSubsBegin))
                        End If
                    End If
                End If
            Next
        Next

        subStr = subStrBuilder.ToString()

        Return subStr

    Catch e As Exception
        Return ""
    End Try
End Function
4

3 回答 3

1

您的代码与正则表达式完全一样!据我所知,您的代码确实没有问题。

在这里,我什至在更严重的情况下对其进行了测试:

Public Sub Main()
    Dim a As String = ""
    Dim str1 As String = "Hi there this is jeff''s dog.-do you recognize this?? This__)=+ is m((a-@-&&*-ry$#@! <>Hi:;? the[]{}re this|\ is jeff''s dog." 'Try to trick the logic!
    Dim str2 As String = "Hi there this is jeff''s dog. ^^^^This__)=+ is m((a-@-&&*-ry$#@! <>Hi:;? the[]{}re this|\ is jeff''s dog."
    LongestCommonSubstring(str1, str2, a)
    Console.WriteLine(a)
    Console.ReadKey()
End Sub

请注意,我将'-$@^_)=+&|\{}[]?!;:.<>所有内容都放在那里。另外,我试图通过给出早期结果来欺骗您的代码。

但是结果非常好!

在此处输入图像描述

您可能会在给您带来问题的输入上放置更多实际样本。否则,您可能会描述您使用/部署代码的环境。也许问题出在其他地方而不是代码中。

于 2015-12-29T03:54:43.063 回答
1

我用 dotnetfiddle 进行了尝试,它正在与您发布的代码一起使用。请在您的项目中激活您的警告。你有没有返回值的函数,你返回一个整数或一个字符串。这是不正确的。你是如何调用你的函数的?

这是我为您测试的示例: https ://dotnetfiddle.net/mVBDQp

于 2015-12-27T10:22:38.710 回答
-1

解决此问题的最快方法是使用转义码并将所有 ' 替换为您使用的任何转义码

于 2015-12-23T01:11:30.620 回答