GO中字符串的ASCII编码

5
在Ruby中,你可以按照以下方式将字符串编码为ASCII:
str.force_encoding('ASCII')

我们如何在Go中实现相同的效果?

2
如果字符串中包含一个超出[0,127]范围之外的字节,您期望会发生什么? - maerics
3个回答

8
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))

https://play.golang.org/p/gLEuWAGglJV


3
一个简化的版本,省略了无效符文,可能看起来像这样:
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
}

-1

检查这个函数

func UtftoAscii(s string) []byte {
    t := make([]byte, utf8.RuneCountInString(s))
    i := 0
    for _, r := range s {
        t[i] = byte(r)
        i++
    }
    return t
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接