Created
May 26, 2018 16:37
-
-
Save ghettoeinstein/48d1c46308c34e28b023973c12cb5822 to your computer and use it in GitHub Desktop.
Reverse and capitalize strings from standard input in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
) | |
func reverseText(s string) string { | |
// Store the length of the string "s" | |
n := len(s) | |
//make a slice of runes of length "n" | |
runes := make([]rune, n) | |
// loop over runes for the length of variable s | |
for _, rune := range s { | |
n-- | |
runes[n] = rune | |
} | |
return strings.ToUpper(string(runes[n:])) | |
} | |
func main() { | |
var f *os.File | |
f = os.Stdin | |
defer f.Close() | |
scanner := bufio.NewScanner(f) | |
for scanner.Scan() { | |
rev := reverseText(scanner.Text()) | |
fmt.Println(">", rev) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was going through "Mastering Go" by Mihalis Tsoukalos, and one of the exercies was to print from a bufio scanner. I wanted to extend the book's code a little bit. So I looked a solution and a small routine to reverse text.
I found a straightforward solution on stackoverflow, and stepped through the code a few times until I figured out exactly what is going on.
Although I don't think I will have much utility in reverse strings and input pieces of text in further programs, this small challenged forces me to think a bit deeper about the algorithms I am using in these toy go scripts.