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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程