Sunday, 12 May 2019

Go language: Generate a random string from fixed characters


Below snippet generates random string from fixed characters.

func GetRandomString(length int) string {
    inputArrayLength := len(InputArray)
    byteArray := make([]rune, length)
    for i := range byteArray {
        byteArray[i] = InputArray[rand.Intn(inputArrayLength)]
    }
    return string(byteArray)
}

App.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

// InputArray : Random string characters are generated from here
var InputArray = []rune("!@#$%^&*()~`{}[]|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

//GetRandomString : return a random string
func GetRandomString(length int) string {
    inputArrayLength := len(InputArray)
    byteArray := make([]rune, length)
    for i := range byteArray {
        byteArray[i] = InputArray[rand.Intn(inputArrayLength)]
    }
    return string(byteArray)
}

func main() {
    str := GetRandomString(20)

    fmt.Println("Random String : ", str)
}

Output
Random String :  @txs$Kt%&X#f*qmvZ#ho


Previous                                                 Next                                                 Home

No comments:

Post a Comment