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

我正在写一个小程序来给段落编号:


以 [1]..., [2].... 的形式将段落编号放在每个段落的前面

应排除文章标题。

这是我的程序:


package main


import (

    "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 byte

prog.go:21: cannot convert "\n" (type string) to type byte

prog.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]

如何将字符串转换为字节?


处理文本的一般做法是什么?读入,按字节或按行解析?


翻阅古今
浏览 260回答 2
2回答

尚方宝剑之说

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

偶然的你

Astring不能以byte有意义的方式转换为 a 。使用以下方法之一:如果您有像 那样的字符串文字"a",请考虑使用像这样的符文文字'a',它可以转换为byte.如果你想拍摄byte出来的string,使用一个索引表达式一样myString[42]。如果要将 a 的内容解释string为(十进制)数字,请使用 strconv.Atoi()或strconv.ParseInt()。请注意,Go 中习惯于编写可以处理 Unicode 字符的程序。解释如何做到这一点对于这个答案来说太过分了,但是有一些教程解释了需要注意的事情。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go