Golang从多行字符串中删除空行的惯用方法

如果我有一个多行字符串


this is a line


this is another line

删除空行的最佳方法是什么?我可以通过拆分、迭代和进行条件检查来使其工作,但有没有更好的方法?


潇湘沐
浏览 1122回答 3
3回答

牧羊人nacy

假设您想要删除空行作为输出的相同字符串,我将使用正则表达式:import (    "fmt"    "regexp")func main() {    var s = `line 1line 2line 3`    regex, err := regexp.Compile("\n\n")    if err != nil {        return    }    s = regex.ReplaceAllString(s, "\n")    fmt.Println(s)}

慕妹3242003

类似于 ΔλЛ 的答案,它可以用字符串来完成。替换:func Replace(s, old, new string, n int) string Replace 返回字符串 s 的副本,其中 old 的前 n 个非重叠实例被 new 替换。如果 old 为空,则它在字符串的开头和每个 UTF-8 序列之后匹配,为 k-rune 字符串生成最多 k+1 次替换。如果 n < 0,则替换次数没有限制。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; var s = `line 1line 2line 3`&nbsp; &nbsp; s = strings.Replace(s, "\n\n", "\n", -1)&nbsp; &nbsp; fmt.Println(s)}https://play.golang.org/p/lu5UI74SLo

慕的地6264312

更通用的方法可能是这样的。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "regexp"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; s := `&nbsp; &nbsp; ####&nbsp;&nbsp; &nbsp; ####&nbsp; &nbsp; ####&nbsp; &nbsp; ####&nbsp; &nbsp; `&nbsp; &nbsp; fmt.Println(regexp.MustCompile(`[\t\r\n]+`).ReplaceAllString(strings.TrimSpace(s), "\n"))}https://play.golang.org/p/uWyHfUIDw-o
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go