在Ruby中,你可以按照以下方式将字符串编码为ASCII:
我们如何在Go中实现相同的效果?
str.force_encoding('ASCII')
我们如何在Go中实现相同的效果?
strconv.QuoteToASCII
QuoteToASCII返回一个双引号括起来的Go字符串文字,表示s。返回的字符串使用Go转义序列(\t、\n、\xFF、\u0100)表示非ASCII字符和由IsPrint定义的不可打印字符。
或者,如果您想要ASCII代码数组,可以这样做:
import "encoding/ascii85"
dst := make([]byte, 25, 25)
dst2 := make([]byte, 25, 25)
ascii85.Encode(dst, []byte("Hello, playground"))
fmt.Println(dst)
ascii85.Decode(dst2, dst, false)
fmt.Println(string(dst2))
func forceASCII(s string) string {
rs := make([]rune, 0, len(s))
for _, r := range s {
if r <= 127 {
rs = append(rs, r)
}
}
return string(rs)
}
// forceASCII("Hello, World!") // => "Hello, World!"
// forceASCII("Hello, 世界!") // => "Hello, !"
// forceASCII("Привет") // => ""
但是如果目标UTF-8字符串包含ASCII字符范围[0,127]
之外的任何字符,您希望有特殊的行为时怎么办?
您可以编写一个函数来处理各种情况,方法是提取一个函数参数,该参数接受无效的ASCII符文并返回字符串替换或错误。
例如(Go Playground):
func forceASCII(s string, replacer func(rune) (string, error)) (string, error) {
rs := make([]rune, 0, len(s))
for _, r := range s {
if r <= 127 {
rs = append(rs, r)
} else {
replacement, err := replacer(r)
if err != nil {
return "", err
}
rs = append(rs, []rune(replacement)...)
}
}
return string(rs), nil
}
func main() {
replacers := []func(r rune) (string, error){
// omit invalid runes
func(_ rune) (string, error) { return "", nil },
// replace with question marks
func(_ rune) (string, error) { return "?", nil },
// abort with error */
func(r rune) (string, error) { return "", fmt.Errorf("invalid rune 0x%x", r) },
}
ss := []string{"Hello, World!", "Hello, 世界!"}
for _, s := range ss {
for _, r := range replacers {
ascii, err := forceASCII(s, r)
fmt.Printf("OK: %q → %q, err=%v\n", s, ascii, err)
}
}
// OK: "Hello, World!" → "Hello, World!", err=<nil>
// OK: "Hello, World!" → "Hello, World!", err=<nil>
// OK: "Hello, World!" → "Hello, World!", err=<nil>
// OK: "Hello, 世界!" → "Hello, !", err=<nil>
// OK: "Hello, 世界!" → "Hello, ??!", err=<nil>
// OK: "Hello, 世界!" → "", err=invalid rune 0x4e16
}
检查这个函数
func UtftoAscii(s string) []byte {
t := make([]byte, utf8.RuneCountInString(s))
i := 0
for _, r := range s {
t[i] = byte(r)
i++
}
return t
}
[0,127]
范围之外的字节,您期望会发生什么? - maerics