DEV Community

Discussion on: Reverse a Word.

Collapse
 
justinenz profile image
Justin

Go! This was a fun challenge as I'm fairly new to Go =) Feedback is welcomed!

package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    var phraseList = os.Args[1:]
    for index := range phraseList {
        fmt.Printf("%s :: %s :: %t\n",
            phraseList[index],
            reverse(phraseList[index]),
            isPalindrome(phraseList[index]))
    }
}

func reverse(phrase string) string {
    var phraseBytes = []byte(phrase)
    var phraseLenght = len(phraseBytes) - 1
    var tempChar byte
    for index := 0; index < len(phraseBytes)/2; index++ {
        tempChar = phraseBytes[index]
        phraseBytes[index] = phraseBytes[phraseLenght-index]
        phraseBytes[phraseLenght-index] = tempChar
    }
    return string(phraseBytes)
}

func isPalindrome(phrase string) bool {
    return strings.Replace(phrase, " ", "", -1) ==
        strings.Replace(reverse(phrase), " ", "", -1)
}

C:\go\src\reverse> .\reverse reverse four three "taco cat"
reverse :: esrever :: false
four :: ruof :: false
three :: eerht :: false
taco cat :: tac ocat :: true