3 回答

TA貢獻1775條經驗 獲得超8個贊
strconv.QuoteToASCII
QuoteToASCII 返回表示 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))

TA貢獻1998條經驗 獲得超6個贊
省略無效符文的簡單版本可能如下所示:
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 符文并返回字符串替換或錯誤的函數參數。
例如(去游樂場):
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
}

TA貢獻1817條經驗 獲得超6個贊
檢查此功能
func UtftoAscii(s string) []byte {
t := make([]byte, utf8.RuneCountInString(s))
i := 0
for _, r := range s {
t[i] = byte(r)
i++
}
return t
}
- 3 回答
- 0 關注
- 310 瀏覽
添加回答
舉報