Write a vb.net program to reverse a string.


動機:
對於給你一個字串,
再要求你寫個function去reverse它,
要如何寫呢?!

說明:
利用 Microsoft Visual Basic 2010 Express 免費軟體,
再撰寫相關的程式即可達到要求, 程式碼如下:
(若重點是要求 algorithm 及 performance 的話,
可能程式碼就要另外思考如何改變了)



Module Module1

    Dim str() As String = {"I", " ", "a", "m", " ", "a", " ", "g", "o", "o", "d", " ", "b", "o", "y"}

    Sub Main()
        Console.Write("Original string : ")
        printContentsOfStringArray(str)

        ' Call the recursion function
        Reverse(0)

        Console.Write("Reversed string : ")
        printContentsOfStringArray(str)

        Console.Write("Press enter to exit.")
        Console.ReadLine()
    End Sub

    Sub Reverse(ByVal pos As Integer)
        If (pos < (str.Length() / 2)) Then
            Dim ch As Char

            ' Swap str[pos] and str[strlen(str) - pos - 1]
            ch = str(pos)
            str(pos) = str(str.Length() - pos - 1)
            str(str.Length() - pos - 1) = ch

            ' Now recurse!
            Reverse(pos + 1)
        End If
    End Sub

    Sub printContentsOfStringArray(ByRef strArrayToPrint() As String)
        For Each strin As String In strArrayToPrint
            Console.Write(strin)
        Next

        Console.WriteLine()
    End Sub
End Module



參攷: Write a C program to reverse a string.

執行檔下載連結: https://docs.google.com/open?id=0B_4eUrknq7N1YWVkMjA1MmQtYTg3Yi00NTVjLWI4YWUtNzk1ZWE2NGM1YTZj

留言