fmt.Sprintf 字符串格式化
tpl := `[%s] Your verify code is %s.`
s := fmt.Sprintf(tpl, "Markjour", "1234")
println(s)
os.Expand 变量替换
tpl := `[${sign}] Your verify code is ${code}.`
params := map[string]string{"sign": "Markjour", "code": "1234"}
println(os.Expand(tpl, func(k string) string { return params[k] }))
text/template 和 html/template
这两个就可以处理复杂的情况,嵌套模板,控制语句都支持。
package main
import (
"os"
"text/template"
)
func main() {
tpl := `[{{.sign}}] Your verify code is {{.code}}.`
t := template.New("just-a-name")
t, _ = t.Parse(tpl)
params := map[string]string{"sign": "Markjour", "code": "1234"}
t.Execute(os.Stdout, params)
}
附:strings.Map
/ bytes.Map
提供单个字符的替换
func Map(mapping func(rune) rune, s string) string
package main
import (
"fmt"
"strings"
)
const A = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \n"
const B = "N'|&4:@ j{BI+Y!H/Q_iR\\FM}$moLe?#X\"WCE3S,8(r1f%T.;6DbaG]y`q~ltJxu-k2gA\nvhnd=)*s7Z5p^OK[V0z>9<UcwP"
func main() {
encrypt := func(r rune) rune {
if !strings.ContainsRune(A, r) {
return 0
}
return rune(B[strings.IndexRune(A, r)])
}
decrypt := func(r rune) rune {
if !strings.ContainsRune(B, r) {
return 0
}
return rune(A[strings.IndexRune(B, r)])
}
raw := "Life was like a box of chocolate, you never know what you're gonna get."
fmt.Println(raw)
encrypted := strings.Map(encrypt, raw)
fmt.Println(encrypted)
// 3j:4wFN_wIjB4wNw'!Mw!:w| !|!INi4dw}!RwY4\4QwBY!FwF Niw}!RAQ4w@!YYNw@4i)
decrypted := strings.Map(decrypt, encrypted)
fmt.Println(decrypted)
}
参考资料与拓展阅读
- CSDN, cheniie, Go 字符串模板替换