我正在寫一個小程序來給段落編號:以 [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 關注
- 292 瀏覽
添加回答
舉報
0/150
提交
取消