Skip to content

Commit fe97a67

Browse files
committed
Add string_random_string example
1 parent ae70df9 commit fe97a67

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

examples/basic/strs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@
1313
| diff_trimright_trimsuffix.go | string_diff_trimright_trimsuffix | strings.TrimRight と strings.TrimSuffix のちょっとした違いについてのサンプルです. |
1414
| using_string_clone.go | string_using_clone | Go 1.18 で追加された strings.Clone() のサンプルです |
1515
| trimspace.go | string_trim_space | strings.TrimSpace() のサンプルです. |
16+
| random_string.go | string_random_string | 指定された文字数のランダム文字列を作成するサンプルです. |

examples/basic/strs/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2323
m["string_cut_prefix_suffix"] = CutPrefixSuffix
2424
m["string_using_clone"] = UsingStringsClone
2525
m["string_trim_space"] = TrimSpace
26+
m["string_random_string"] = RandomString
2627
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package strs
2+
3+
import (
4+
"math/rand"
5+
"time"
6+
7+
"github.com/devlights/gomy/output"
8+
)
9+
10+
// RandomString は、指定された文字数のランダム文字列を作成するサンプルです.
11+
//
12+
// # REFERENCES
13+
// - https://gist.github.com/devlights/7534500bfe62c566bf944553ae8974e8
14+
func RandomString() error {
15+
const (
16+
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
17+
)
18+
19+
var (
20+
buf = make([]byte, 1<<6)
21+
unixNano = time.Now().UnixNano()
22+
rndSource = rand.NewSource(unixNano)
23+
rnd = rand.New(rndSource)
24+
)
25+
26+
for i := range buf {
27+
buf[i] = charset[rnd.Intn(len(charset))]
28+
}
29+
30+
output.Stdoutl("[output]", string(buf))
31+
32+
return nil
33+
34+
/*
35+
$ task
36+
task: [build] go build .
37+
task: [run] ./try-golang -onetime
38+
39+
ENTER EXAMPLE NAME: string_random_string
40+
41+
[Name] "string_random_string"
42+
[output] 0OWayZgY57QSJKHvAl8ePRtFSFGtgKJRug6OFdN3XL17oxUW2pqmCaGpGqYV2oEY
43+
44+
[Elapsed] 28.55µs
45+
*/
46+
}

0 commit comments

Comments
 (0)