最常见的子串破坏问题

时间:2015-12-23 01:05:01

标签: vb.net string compare longest-substring

您好我有一个函数可以找到两个字符串之间最长的公共子字符串。它的效果很好,除非它达到任何单引号时似乎会中断:'

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

有人可以帮我调整这个功能,所以它在子字符串中包含单引号吗?我知道它需要在某个地方逃脱,我只是不确定在哪里。

实施例: 字符串1:你好,这是杰夫的狗。 字符串2:你好,这是杰夫的狗。

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

编辑:似乎也发生在" - "同样。

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

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

3 个答案:

答案 0 :(得分:1)

我尝试使用dotnetfiddle,并且正在使用您发布的代码。请在项目中激活您的警告。你有没有返回值的函数,你返回一个整数或一个字符串。这是不正确的。你怎么称呼你的功能?

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

答案 1 :(得分:1)

您的代码与正则表达式一样完全!据我所知,您的代码确实存在 nothing 错误。

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

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

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

但结果非常好!

enter image description here

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

答案 2 :(得分:-1)

解决此问题的最快方法是使用转义码并替换所有&#39;使用你使用的任何转义码

相关问题