2 回答

TA貢獻2051條經驗 獲得超10個贊
首先,原型bufio.ReadString是
func (b *Reader) ReadString(delim byte) (line string, err error)
它只能將一個字節作為 arg,因此您的;\n分隔符將不起作用。
使用;作為分隔符來代替。
但是如果你使用ReadString(';')它會在你的結果中包含其他字符,比如 '\n'
一個例子:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
const raw = `select * from table1;
select *
from table2;
select 1;`
br := bufio.NewReader(strings.NewReader(raw))
var err error
var s string
err = nil
for err == nil {
s, err = br.ReadString(';')
if err == nil {
fmt.Printf("%q", s)
}
}
這將得到:
"select * from table1;"" \nselect * \nfrom table2;""\n\nselect 1;"
解決方案:
使用Scanner可能更方便,實現如下。
ps:;將被視為單詞的一部分
package main
import (
"bufio"
"fmt"
"os"
"strings"
"bytes"
)
func main() {
const raw = `select * from table1;
select *
from table2;
select 1;`
scanner := bufio.NewScanner(strings.NewReader(raw))
scanner.Split(bufio.ScanWords)
var tmpbuf bytes.Buffer
for scanner.Scan() {
w := scanner.Text()
tmpbuf.WriteString(w)
if w[len(w)-1] == ';' {
tmpbuf.WriteString("\n")
fmt.Printf(tmpbuf.String())
tmpbuf.Reset()
} else {
tmpbuf.WriteString(" ")
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
}
你會得到:
select * from table1;
select * from table2;
select 1;

TA貢獻1775條經驗 獲得超8個贊
您可以使用bufio.Scanner
:https : //golang.org/pkg/bufio/#Scanner 查看行示例:https : //golang.org/pkg/bufio/#example_Scanner_lines
- 2 回答
- 0 關注
- 276 瀏覽
添加回答
舉報