golang生成指定位數的字符串(數字、大小寫字母)


package main
 
import(
    "fmt"
    "time"
    "math/rand"
)
 
const (
    KC_RAND_KIND_NUM   = 0  // 純數字
    KC_RAND_KIND_LOWER = 1  // 小寫字母
    KC_RAND_KIND_UPPER = 2  // 大寫字母
    KC_RAND_KIND_ALL   = 3  // 數字、大小寫字母
)
 
// 隨機字符串
func Krand(size int, kind int) []byte {
    ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
    is_all := kind > 2 || kind < 0
    rand.Seed(time.Now().UnixNano())
    for i :=0; i < size; i++ {
        if is_all { // random ikind
            ikind = rand.Intn(3)
        }
        scope, base := kinds[ikind][0], kinds[ikind][1]
        result[i] = uint8(base+rand.Intn(scope))
    }
    return result
}
 
func main(){
    fmt.Println("num:   " + string(Krand(16, KC_RAND_KIND_NUM)))
    fmt.Println("lower: " + string(Krand(16, KC_RAND_KIND_LOWER)))
    fmt.Println("upper: " + string(Krand(16, KC_RAND_KIND_UPPER)))
    fmt.Println("all:   " + string(Krand(16, KC_RAND_KIND_ALL)))
}

運行效果:
num: 1724754808278598
lower: rvuwvrmamuafuxpg
upper: RVUWVRMAMUAFUXPG
all: VWrA875Gg80U07GP
 

 原文引自:https://www.oschina.net/code/snippet_170216_50650


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM