dstbtam8732 2017-08-21 07:49
浏览 512
已采纳

如何从golang的数组中提取字符?

need to extract the random characters from string

here is what i got:

const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  b := make([]byte, 1)
for i := range b {
    b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
fmt.Println(string(b))

but it always returns "X" but, i need to return every time new character using rand function. any help would be really appreciated. Thanks.

  • 写回答

2条回答 默认 最新

  • duan7772 2017-08-21 08:12
    关注

    Start by seeding the pseudorandom number generator. For example,

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func main() {
        rand.Seed(time.Now().UnixNano())
        const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        b := make([]byte, 7)
        for i := range b {
            b[i] = letterBytes[rand.Intn(len(letterBytes))]
        }
        fmt.Println(string(b))
    }
    

    Output:

    jfXtySC
    

    The Go Playground

    About the Playground

    In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output.

    Therefore, in the Go playground, time.Now().UnixNano() always returns the same value. For a random seed value, run the code on your computer.


    For any Unicode code point (Go rune),

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func main() {
        rand.Seed(time.Now().UnixNano())
        chars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ世界!@=")
        r := make([]rune, 50)
        for i := range r {
            r[i] = chars[rand.Intn(len(chars))]
        }
        fmt.Println(string(r))
    }
    

    Output:

    世QRYSp=@giJMIKly=tXRefjtVkeE!yHhTSQHvLyUYdRNIBbILW
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?