如何更改字符串中某些位置的字符

对于像“AA_BB_CC”这样的字符串,我想把它变成“AaBbCc”。我以为我可以这样做:


func CapsToCamel() string {

  var buf bytes.Buffer

  s := "AA_BB_CC"

  toUpper := true

  for i :=0; i<len(s); i++ {

    if toUpper {

       buf.WriteString(strings.ToUpper(s[i])) // error: s[i] is of byte.

    ...

}

我停在那里,虽然我可以将每个s[i]视为 ASCII 字符,然后将其值与aand进行比较z,但我认为应该有一个 Go 方法来做到这一点。


泛舟湖上清波郎朗
浏览 177回答 1
1回答

繁星淼淼

这是一个更清洁的工作解决方案,仅使用strings包而不必依赖使用bytes.Buffer.func CapsToCamel(s string) string {&nbsp; &nbsp; newstr := ""&nbsp; &nbsp; str := []byte(strings.Join(strings.Split(s, "_"), ""))&nbsp; &nbsp; for i := 0; i < len(str); i += 2 {&nbsp; &nbsp; &nbsp; &nbsp; newstr += string(str[i])&nbsp; &nbsp; &nbsp; &nbsp; newstr += strings.ToLower(string(str[i]))&nbsp; &nbsp; }&nbsp; &nbsp; return newstr}操场上也有一个简单的例子:https: //play.golang.org/p/1YIeTlr8a6D
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go