为了账号安全,请及时绑定邮箱和手机立即绑定

Go中的文本处理 - 如何将字符串转换为字节?

Go中的文本处理 - 如何将字符串转换为字节?

Go
翻阅古今 2021-09-10 18:12:41
我正在写一个小程序来给段落编号:以 [1]..., [2].... 的形式将段落编号放在每个段落的前面应排除文章标题。这是我的程序:package mainimport (    "fmt"    "io/ioutil")var s_end = [3]string{".", "!", "?"}func main() {    b, err := ioutil.ReadFile("i_have_a_dream.txt")    if err != nil {        panic(err)    }    p_num, s_num := 1, 1    for _, char := range b {        fmt.Printf("[%s]", p_num)        p_num += 1        if char == byte("\n") {            fmt.Printf("\n[%s]", p_num)            p_num += 1        } else {            fmt.Printf(char)        }    }}http://play.golang.org/p/f4S3vQbglY我收到此错误:prog.go:21: cannot convert "\n" to type byteprog.go:21: cannot convert "\n" (type string) to type byteprog.go:21: invalid operation: char == "\n" (mismatched types byte and string)prog.go:25: cannot use char (type byte) as type string in argument to fmt.Printf[process exited with non-zero status]如何将字符串转换为字节?处理文本的一般做法是什么?读入,按字节或按行解析?
查看完整描述

2 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

using"\n"导致它被视为一个数组,use'\n'将它视为一个单一的字符。


查看完整回答
反对 回复 2021-09-10
?
偶然的你

TA贡献1841条经验 获得超3个赞

Astring不能以byte有意义的方式转换为 a 。使用以下方法之一:

  • 如果您有像 那样的字符串文字"a",请考虑使用像这样的符文文字'a',它可以转换为byte.

  • 如果你想拍摄byte出来的string,使用一个索引表达式一样myString[42]

  • 如果要将 a 的内容解释string为(十进制)数字,请使用 strconv.Atoi()strconv.ParseInt()

请注意,Go 中习惯于编写可以处理 Unicode 字符的程序。解释如何做到这一点对于这个答案来说太过分了,但是有一些教程解释了需要注意的事情。


查看完整回答
反对 回复 2021-09-10
  • 2 回答
  • 0 关注
  • 259 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信