dongtuan1594 2016-01-15 01:41
浏览 215
已采纳

我可以将字符串作为bufio.ReadString()的分隔符吗?

I have a file which contains multi-line queries. I wanted to read them one by one and print them. Something like :

temp.sql

select * from table1;  
select *  
from table2;

select 1; 

Since i can have multiline queries I wanted to use ; as the delimiter. Is that possible ? Is there a better method that i can use instead of bufio.ReadString ?

  • 写回答

2条回答 默认 最新

  • dousuiguang9328 2016-01-15 03:28
    关注

    firstly, the prototype of bufio.ReadString is

     func (b *Reader) ReadString(delim byte) (line string, err error)
    

    it can only take one byte as arg, so your ; delimiter won't work.

    use ; as delimiter instead.

    But if you use ReadString(';') it will contain other characters in your results, such as ' '

    a example:

    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)
            }
    
        }
    

    this will get:

    "select * from table1;""  
    select *  
    from table2;""
    
    select 1;"
    

    online test

    Solution:

    use Scanner may be more convenient, and achieve this as bellow.

    ps: ; will be considered as part of words

    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("
    ")
                fmt.Printf(tmpbuf.String())
                tmpbuf.Reset()
            } else {
                tmpbuf.WriteString(" ")
            }
        }
        if err := scanner.Err(); err != nil {
            fmt.Fprintln(os.Stderr, "reading input:", err)
        }
    }
    

    you will get:

    select * from table1;
    select * from table2;
    select 1;
    

    online test

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?