可以使用正则表达式和strings包中的方法来实现:


package main
import (
    "fmt"
    "regexp"
    "strings"
)
func main() {
    str := "hello world go lang"
    re := regexp.MustCompile(`\s([^\s]*)$`)
    matched := re.FindStringSubmatch(str)
    if len(matched) > 1 {
        replaced := strings.Replace(str, matched[1], "-", 1)
        fmt.Println(replaced)
    }
}

输出为:


hello world go-lang

解释:

\s([^\s]*)$
FindStringSubmatch
Replace-