GO中字符串的ASCII编码 [英] ASCII encoding for string in GO

查看:90
本文介绍了GO中字符串的ASCII编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,您可以按以下方式将字符串编码为ASCII:

In Ruby, you can encode string to ASCII as follows:

str.force_encoding('ASCII')

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

How can we achieve the same in Go?

推荐答案

strconv.QuoteToASCII

QuoteToASCII返回表示s的双引号Go字符串文字.返回的字符串对IsASCII定义的非ASCII字符和不可打印的字符使用Go转义序列(\ t,\ n,\ xFF,\ u0100).

QuoteToASCII returns a double-quoted Go string literal representing s. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII characters and non-printable characters as defined by IsPrint.

或者,如果您想要一个ascii码数组,可以这样做

Or if you want an array of ascii codes, you could do

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

这篇关于GO中字符串的ASCII编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆