duanbiyi7319 2016-08-22 11:40 采纳率: 100%
浏览 48
已采纳

如何在Golang中用div包装每行?

I have a text paragraph.

I would like to wrap each line with a div.

For example if the text string looks like this

Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 

Nam eget lectus porta metus aliquam tincidunt sed vel enim.

Then I would like to wrap it like this

<div>Lorem ipsum dolor sit amet,</div> 
<div>consectetur adipiscing elit.</div> 
<div><br/></div>
<div>Nam eget lectus porta metus aliquam tincidunt sed vel enim.</div>

Can someone tell me what is the proper way?

Thanks

  • 写回答

2条回答 默认 最新

  • dongxie1907 2016-08-22 12:06
    关注

    You may use bytes.Buffer and bufio.NewScanner, like this working sample code:

    package main
    
    import "fmt"
    import "strings"
    import "bufio"
    import "bytes"
    
    func main() {
        r := strings.NewReader(`Lorem ipsum dolor sit amet,
    consectetur adipiscing elit.
    
    Nam eget lectus porta metus aliquam tincidunt sed vel enim.`)
    
        buf := &bytes.Buffer{}
        scanner := bufio.NewScanner(r)
        for scanner.Scan() {
            s := scanner.Text()
            if len(s) == 0 {
                s = `<br/>`
            }
            buf.WriteString(`<div>` + s + `</div>
    `)
        }
        fmt.Println(buf.String())
    }
    

    output:

    <div>Lorem ipsum dolor sit amet,</div>
    <div>consectetur adipiscing elit.</div>
    <div><br/></div>
    <div>Nam eget lectus porta metus aliquam tincidunt sed vel enim.</div>
    

    You may use bytes.Buffer and html/template,
    but you have <div></div> instead of <div><br/></div>, then you may use

    s = strings.Replace(s, `<div></div>`, `<div><br/></div>`, -1)
    

    like this working sample code:

    package main
    
    import "fmt"
    import "bytes"
    import "html/template"
    import "strings"
    
    func main() {
        r := []string{`Lorem ipsum dolor sit amet,`,
            `consectetur adipiscing elit.`,
            ``,
            `Nam eget lectus porta metus aliquam tincidunt sed vel enim.`}
        buf := &bytes.Buffer{}
        t := template.Must(template.New("template").Parse("{{range .}}<div>{{.}}</div>
    {{end}}"))
        t.Execute(buf, r)
        s := buf.String()
        s = strings.Replace(s, `<div></div>`, `<div><br/></div>`, -1)
        fmt.Println(s)
    }
    

    output:

    <div>Lorem ipsum dolor sit amet,</div>
    <div>consectetur adipiscing elit.</div>
    <div><br/></div>
    <div>Nam eget lectus porta metus aliquam tincidunt sed vel enim.</div>
    

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部