20

Golang中生成随机字符串并复制到粘贴板

 4 years ago
source link: https://studygolang.com/articles/25520
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前段时间在生活中偶尔需要对某些文件进行重命名,而且是随机名字,刚

开始是手动重命名然后在键盘上胡乱打一些字母数字,时间长了发现也挺麻烦的,于是想到能不能用golang实现这个功能并且自动把生成的字符串

复制到粘贴板,然后生成exe文件,要用的是直接鼠标双击就行。说干就干。

网上搜了些相关资料,于是写了出来。

安装必要的库

go get github.com/atotto/clipboard

代码实现

package main

import (
    "fmt"
    "github.com/atotto/clipboard"
    "math/rand"
    "strings"
    "time"
)

var a = [...]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
    "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

func main() {
    s := g()
    fmt.Println(s)
    //复制内容到剪贴板
    clipboard.WriteAll(s)
}

func g() string {
    var builder strings.Builder
    for i := 0; i < 10; i++ {
        rand.Seed(time.Now().UnixNano())
        time.Sleep(1 * time.Nanosecond)
        c := rand.Intn(36)
        builder.WriteString(a[c])
    }
    return builder.String()
}

我这里是随机生成10个字符,你也可以自己改。

最后生成了exe文件,要用的时候双击一下,你的粘贴板里就有了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK