问题描述
如果我有多行字符串,例如
If I have a multi line string like
this is a line
this is another line
删除空行的最佳方法是什么?我可以通过拆分,迭代和进行条件检查来使其工作,但是还有更好的方法吗?
what is the best way to remove the empty line? I could make it work by splitting, iterating, and doing a condition check, but is there a better way?
推荐答案
假定您要删除输出的空行作为输出的相同字符串,我将使用正则表达式:
Assumming that you want to have the same string with empty lines removed as an output, I would use regular expressions:
import (
"fmt"
"regexp"
)
func main() {
var s = `line 1
line 2
line 3`
regex, err := regexp.Compile("\n\n")
if err != nil {
return
}
s = regex.ReplaceAllString(s, "\n")
fmt.Println(s)
}
这篇关于Golang惯用方式从多行字符串中删除空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!