GO中字符串的ASCII编码

在 Ruby 中,您可以将字符串编码为 ASCII,如下所示:

str.force_encoding('ASCII')

我们如何在 Go 中实现相同的目标?


天涯尽头无女友
浏览 231回答 3
3回答

www说

strconv.QuoteToASCIIQuoteToASCII 返回表示 s 的双引号 Go 字符串文字。返回的字符串对 IsPrint 定义的非 ASCII 字符和不可打印字符使用 Go 转义序列(\t、\n、\xFF、\u0100)。或者如果你想要一组 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 {&nbsp; rs := make([]rune, 0, len(s))&nbsp; for _, r := range s {&nbsp; &nbsp; if r <= 127 {&nbsp; &nbsp; &nbsp; rs = append(rs, r)&nbsp; &nbsp; }&nbsp; }&nbsp; return string(rs)}// forceASCII("Hello, World!") // => "Hello, World!"// forceASCII("Hello, 世界!") // => "Hello, !"// forceASCII("Привет") // => ""但是,如果目标 UTF-8 字符串包含 ASCII 字符范围之外的任何字符,您想要特殊行为怎么办[0,127]?您可以编写一个函数来处理各种情况,方法是提取一个采用无效 ASCII 符文并返回字符串替换或错误的函数参数。例如(去游乐场):func forceASCII(s string, replacer func(rune) (string, error)) (string, error) {&nbsp; rs := make([]rune, 0, len(s))&nbsp; for _, r := range s {&nbsp; &nbsp; if r <= 127 {&nbsp; &nbsp; &nbsp; rs = append(rs, r)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; replacement, err := replacer(r)&nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; rs = append(rs, []rune(replacement)...)&nbsp; &nbsp; }&nbsp; }&nbsp; return string(rs), nil}func main() {&nbsp; replacers := []func(r rune) (string, error){&nbsp; &nbsp; // omit invalid runes&nbsp; &nbsp; func(_ rune) (string, error) { return "", nil },&nbsp; &nbsp; // replace with question marks&nbsp; &nbsp; func(_ rune) (string, error) { return "?", nil },&nbsp; &nbsp; // abort with error */&nbsp; &nbsp; func(r rune) (string, error) { return "", fmt.Errorf("invalid rune 0x%x", r) },&nbsp; }&nbsp; ss := []string{"Hello, World!", "Hello, 世界!"}&nbsp; for _, s := range ss {&nbsp; &nbsp; for _, r := range replacers {&nbsp; &nbsp; &nbsp; ascii, err := forceASCII(s, r)&nbsp; &nbsp; &nbsp; fmt.Printf("OK: %q → %q, err=%v\n", s, ascii, err)&nbsp; &nbsp; }&nbsp; }&nbsp; // OK: "Hello, World!" → "Hello, World!", err=<nil>&nbsp; // OK: "Hello, World!" → "Hello, World!", err=<nil>&nbsp; // OK: "Hello, World!" → "Hello, World!", err=<nil>&nbsp; // OK: "Hello, 世界!" → "Hello, !", err=<nil>&nbsp; // OK: "Hello, 世界!" → "Hello, ??!", err=<nil>&nbsp; // OK: "Hello, 世界!" → "", err=invalid rune 0x4e16}

慕的地6264312

检查此功能func UtftoAscii(s string) []byte {&nbsp; &nbsp; t := make([]byte, utf8.RuneCountInString(s))&nbsp; &nbsp; i := 0&nbsp; &nbsp; for _, r := range s {&nbsp; &nbsp; &nbsp; &nbsp; t[i] = byte(r)&nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; }&nbsp; &nbsp; return t}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go