golang中的字符串转换基于分隔符

时间:2018-04-30 07:25:07

标签: go

假设我有一个字符串" a-b-c-d",如果字符串由" - "分隔,我想替换" - " by":"否则我希望字符串保持不变。我怎么在Go中做到这一点?

package main

import (
    "fmt"
    "strings"
)

func main() {
    data := "01-12-13-14-15-16"
    //  mac :="11:11:11:11:11:11"

    // Split on comma.
    result := strings.Split(data, "-")
    result1 :=strings.Join(result,":")

    //  result11 := strings.Split(mac, "-")
    //result12 :=strings.Join(mac,":")

    fmt.Print(result1)
    //fmt.Print(result12)
}

1 个答案:

答案 0 :(得分:4)

标准库中有strings.Replace函数:

result1 := strings.Replace(data, "-", ":", -1)