【发布时间】:2017-09-28 19:35:22
【问题描述】:
所以我以字符串形式的消息开始,将其转换为字节数组并打印出来,我现在丢失了原始字符串,但得到了字节数组的字符串输出。我想要我的弦回来。 (不要问我为什么这样做或如何...我真的没有,这只是为了说明目的)。
本质上,我缺少的位是将字节数组的打印表示转换回字节数组的便捷方法。
请参阅下面的示例以更好地解释我正在尝试做的事情(完成“otherWay”功能):
package main
import (
"fmt"
)
func main() {
// started with originalString and lost it
originalString := "I'm a string I am!"
// I have the output of 'oneWay()' in my clipboard, so could paste into code
golangStringFormatOfByteArray := oneWay(originalString)
fmt.Println("String as bytes:", golangStringFormatOfByteArray )
// get original string back
returnString := otherWay(golangStringFormatOfByteArray )
fmt.Println("Original String:", returnString )
}
func oneWay(theString string) string {
theStringAsBytes := []byte(theString)
golangStringFormatOfByteArray := fmt.Sprintf("%v", theStringAsBytes)
return golangStringFormatOfByteArray
}
func otherWay(stringFormat string) string {
// how do I get the original string back
return "I want you back"
}
【问题讨论】:
-
你可以做
string(byteArray)。字符串被简单地定义为[]byte,所以简单的转换就可以了。 -
你的意思是:不是我的原始字符串 - play.golang.org/p/cw39ai7S5_
-
你没有将你的字符串转换成它对应的字节片,你正在变成另一个字符串,它恰好是打印字节片的默认 go 格式。你到底想做什么?
-
如果您以某种方式打印以进行调试,只需打印即可,但不要用您的调试值覆盖原始值。
-
如果打印原始字符串有问题,请考虑使用 %q 格式说明符打印并使用 godoc.org/strconv#Unquote 恢复原始字符串。另一种方法是使用 %x 打印并使用 godoc.org/encoding/hex#DecodeString 恢复原件。
标签: go