您可以使用bytes.Buffer
和bufio.NewScanner
,像這樣的工作示例代碼:
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())
}
輸出:
<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>
您可以使用bytes.Buffer
和html/template
,
但你必須<div></div>
代替<div><br/></div>
,那麼你可以使用
s = strings.Replace(s, `<div></div>`, `<div><br/></div>`, -1)
這樣的工作示例代碼:
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>\n{{end}}"))
t.Execute(buf, r)
s := buf.String()
s = strings.Replace(s, `<div></div>`, `<div><br/></div>`, -1)
fmt.Println(s)
}
輸出:
<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>
文本存儲在變量或文件中嗎?你有什麼嘗試? –
@DavidCullen它存儲在一個變量中。答案有幫助。謝謝 – user1091558