Results 1 to 2 of 2

Thread: string negator

  1. #1

    Thread Starter
    Member
    Join Date
    Oct 2023
    Posts
    46

    string negator

    Code:
    Function Negate(sentence As String) As String
        ' Check if the sentence contains "not"
        If sentence.Contains("not") Then
            Return sentence.Replace("not", "").Trim()
        Else
            ' Replace specific words with their negative forms
            Dim replacements As New Dictionary(Of String, String) From {
                {"i ", "i do "},
                {"he ", "he does "},
                {" it ", " it does "},
                {"is", "is not"},
                {" am", " am not"},
                {" are", " are not"},
                {"does", "does not"},
                {"do ", "do not "},
                {"may", "may not"},
                {"might", "might not"},
                {"could", "could not"},
                {"would", "would not"},
                {"will", "will not"},
                {"has ", "has not "},
                {"have ", "have not "}
            }
    
            For Each kvp As KeyValuePair(Of String, String) In replacements
                sentence = sentence.Replace(kvp.Key, kvp.Value)
            Next
    
            If Not sentence.Contains("not") Then
                Return "not " & sentence
            End If
        End If
    
        Return sentence
    End Function

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,372

    Re: string negator

    I wanted to point out that this code sample does not pass simple unit testing. For example:
    Code:
    Dim testSentence As String = "I am not a woman, therefore I am a man."
    Dim passSentence As String = "I am a woman, therefore I am not a man."
    Dim negatedTest As String = Negate(testSentence)
    
    negatedTest.AssertEquals(testSentence) ' fails
    Demo: https://dotnetfiddle.net/BD9pfp

    The reason it fails is because it incorrectly handles whitespace, it completely ignores casing, and it also fails to consider a negated word with a non-negated word in a single sentence.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width