-
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
-
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.