Golang idiomatic way to remove a blank line from a multi-line string

浪子不回头ぞ 提交于 2020-05-15 02:52:06

问题


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?


回答1:


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)
}



回答2:


Similar to ΔλЛ's answer it can be done with strings.Replace:

func Replace(s, old, new string, n int) string Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements.

package main

import (
    "fmt"
    "strings"
)

func main() {

    var s = `line 1
line 2

line 3`

    s = strings.Replace(s, "\n\n", "\n", -1)

    fmt.Println(s)
}

https://play.golang.org/p/lu5UI74SLo




回答3:


The more generic approach would be something like this maybe.

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    s := `


    #### 

    ####




    ####


    ####




    `

    fmt.Println(regexp.MustCompile(`[\t\r\n]+`).ReplaceAllString(strings.TrimSpace(s), "\n"))
}

https://play.golang.org/p/uWyHfUIDw-o



来源:https://stackoverflow.com/questions/35360080/golang-idiomatic-way-to-remove-a-blank-line-from-a-multi-line-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!