dtqi87613
2019-01-10 12:02 阅读 37
已采纳

如何使用golang替换字符串

I am Making a command line tool for sending an email where I am using urfave/cli package from golang i had made the application where everything is working properly but got stuck with one string replacement part.

Basically, I want to convert a string

info@gmail.com,vik@hotmail.com,myemailid@yahoo.com

to

"info@gmail.com","vik@hotmail.com","myemailid@yahoo.com"

I tried regex substitution but that didn't give me an accurate result. so I manipulate my code where I used String.Split separated by ',' but after that the look around got complex. can anyone help me with this

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongmiao4733 dongmiao4733 2019-01-10 12:12

    To convert the value, simply run something like:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        input := "info@gmail.com,vik@hotmail.com,myemailid@yahoo.com"
        emails := strings.Join(Map(strings.Split(input, ","), func(in string) string {
            return fmt.Sprintf(`"%s"`, in)
        }), ",")
    
        fmt.Printf("%v", emails)
    }
    
    func Map(vs []string, f func(string) string) []string {
        vsm := make([]string, len(vs))
        for i, v := range vs {
            vsm[i] = f(v)
        }
        return vsm
    }
    

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

    Good luck.

    点赞 评论 复制链接分享

相关推荐