Golang惯用方式从多行字符串中删除空白行

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("

")
    if err != nil {
        return
    }
    s = regex.ReplaceAllString(s, "
")

    fmt.Println(s)
}

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, "

", "
", -1)

    fmt.Println(s)
}

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

The more generic approach would be something like this maybe.

package main

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

func main() {
    s := `


    #### 

    ####




    ####


    ####




    `

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

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