Home > database >  In Golang How to generate a random string of random length within range without integers
In Golang How to generate a random string of random length within range without integers

Time:03-16

I tried to remove the integer from the generated string with regex but this will not give me the length within the range required( many will be less than the minimum )

package main

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

func randomString(length int) string {
    rand.Seed(time.Now().UnixNano())
    b := make([]byte, length)
    rand.Read(b)
    return fmt.Sprintf("%x", b)[:length]
}
func randomLength(minL, maxL int) int {
    rand.Seed(time.Now().UnixNano())

    return rand.Intn(maxL-minL)   minL
}

func main() {
    reg, err := regexp.Compile("[^a-zA-Z] ")
    if err != nil {
        log.Fatal(err)
    }

    for i := 0; i < 10; i   {
        processedString := reg.ReplaceAllString(randomString(randomLength(8, 16)), "")
        println(processedString)

    }

}

Edit: when I searched for the question I missed detailed @icza answer in that question.

CodePudding user response:

var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))

func StringWithCharset(length int, charset string) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[seededRand.Intn(len(charset)-1)]
    }
    return string(b)
}

func main() {
    rangeStart := 0
    rangeEnd := 10
    offset := rangeEnd - rangeStart
    randLength := seededRand.Intn(offset)   rangeStart

    charSet := "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
    randString := StringWithCharset(randLength, charSet)
}

CodePudding user response:

You just need to define the alphabet that you're using. Something like the following (You can fiddle with it here in the Go Playground).

package main

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

func main() {

  rand.Seed(time.Now().UnixNano())

  var alphabet []rune = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

  rs := randomString(20, alphabet)
  fmt.Printf("This is pretty random: %s\n", rs)

}

func randomString(n int, alphabet []rune) string {

  alphabetSize := len(alphabet)
  var sb strings.Builder

  for i := 0; i < n; i   {
    ch := alphabet[rand.Intn(alphabetSize)]
    sb.WriteRune(ch)
  }

  s := sb.String()
  return s
}
  • Related