Mortimer is taking up TDD, and starts a new project by writing the following test.
<TestMethod()> _ Public Sub CanReverseString() Dim input As String = "OdeToCode" Dim result As String = Utility.ReverseString(input) Assert.AreEqual("edoCoTedO", result) End Sub
Yes, it's another one of those big projects that reverses strings all the time.
With a test in place, Mortimer writes the following stub.
Public Class Utility Public Shared Function ReverseString( _ ByVal input As String) As String Return Nothing End Function End Class
Good news - the test fails! Now it's time to provide a real implementation...
Public Class Utility Public Shared Function ReverseString( _ ByVal input As String) As String Dim chars As Char() chars = New Char(input.Length) {} For i As Integer = 0 To input.Length - 1 chars(i) = input(input.Length - i - 1) Next Return New String(chars) End Function End Class
Mortimer thinks he has everything straight - but the test still fails! What could be wrong with Mortimer's ReverseString?
Comments
You should notice an extra character in the reverse string.
An unprintable character...
chars = New Char(input.Length-1) {}
Notice the "-1". This is different than C#.
That's very odd. Let's exchange project files. My address is scott at OdeToCode.com
If that random character happens to be a zero (which in theory should happen no less than 1 in 256 trials, but in practice probably occurs much more often), you will accidentally get a correct string.