Golang : Randomize letters from a string example
For this short tutorial, we will learn how to randomize the letters(including symbols and empty spaces) in a string. Such as:
"Hello World!"
to
" ! WoHllderlo"
Basically, the idea is to convert the string into a slice, randomize(shuffle) the elements inside the slice and then convert the slice back into a string.
Here you go!
package main
import (
"fmt"
"math/rand"
"strings"
"text/scanner"
"time"
)
func breakToCharSlice(str string) []string {
tokens := []rune(str)
var result []string
for _, char := range tokens {
result = append(result, scanner.TokenString(char))
}
return result
}
func shuffle(src []string) []string {
final := make([]string, len(src))
rand.Seed(time.Now().UTC().UnixNano())
perm := rand.Perm(len(src))
for i, v := range perm {
final[v] = src[i]
}
return final
}
func main() {
str := "Hello World!"
//strSlice := strings.Fields(str)
// we want to break the string into individual characters slice
// https://www.socketloop.com/tutorials/golang-break-string-into-a-slice-of-characters-example
strSlice := breakToCharSlice(str)
fmt.Println("Original :", str)
//fmt.Println("Converted to slice :", strSlice)
randomized := shuffle(strSlice)
// convert the slice back to string
randomizedStr := strings.Join(randomized, "")
// get rid the extra ""
randomizedStr = strings.Replace(randomizedStr, "\"", "", -1)
fmt.Printf("Randomized : %s\n", randomizedStr)
}
Some sample outputs:
>$ go run randomizeletters.go
>Original : Hello World!
>Randomized : Hlledr! lWoo
>$ go run randomizeletters.go
>Original : Hello World!
>Randomized : rdlollH oe!W
Reference:
https://www.socketloop.com/tutorials/golang-break-string-into-a-slice-of-characters-example
See also : Golang : Break string into a slice of characters example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.7k Golang : Extract XML attribute data with attr field tag example
+6.6k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+4.2k Golang : PGX CopyFrom to insert rows into Postgres database
+4.3k JavaScript: Add marker function on Google Map
+19.3k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+32.2k Golang : How to check if a date is within certain range?
+15.4k Golang : Read a file line by line
+16.9k Golang : Clone with pointer and modify value
+12.8k Facebook PHP getUser() returns 0
+14.5k Golang : How to check if IP address is in range
+8.5k Golang : automatically figure out array length(size) with three dots
+50.1k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate