我正在写一个小程序来给段落编号:以 [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贡献1841条经验 获得超3个赞
Astring
不能以byte
有意义的方式转换为 a 。使用以下方法之一:
如果您有像 那样的字符串文字
"a"
,请考虑使用像这样的符文文字'a'
,它可以转换为byte
.如果你想拍摄
byte
出来的string
,使用一个索引表达式一样myString[42]
。如果要将 a 的内容解释
string
为(十进制)数字,请使用strconv.Atoi()
或strconv.ParseInt()
。
请注意,Go 中习惯于编写可以处理 Unicode 字符的程序。解释如何做到这一点对于这个答案来说太过分了,但是有一些教程解释了需要注意的事情。
- 2 回答
- 0 关注
- 259 浏览
添加回答
举报
0/150
提交
取消