I'm beginner trainee in Go. I can't figure out how not just replace a symbol, but to make next letter Uppercase in Go.
Task: Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
I tried to implement regexp methods with:
re, _ := regexp.Compile(`/[-_]\w/ig`)
res := re.FindAllStringSubmatch(s, -1)
return res
But i can't return res because it's slice/array, but i need to return just string.
My code:
package main
import (
"fmt"
"strings"
)
func ToCamelCase(s string) string {
s = strings.ReplaceAll(s, "-", "")
s = strings.ReplaceAll(s, "_", "")
return s
}
func main() {
var s string
fmt.Scan(&s)
fmt.Println(ToCamelCase(s))
}
Input: "the-stealth-warrior" or "the_stealth_warrior"
Output: "theStealthWarrior" or "TheStealthWarrior"
My Output: thestealthwarrior
CodePudding user response:
You need to define the regex without regex delimiters in Go string literals, and it is more convenient to use the ReplaceAllStringFunc
function:
package main
import (
"fmt"
"regexp"
"strings"
)
func ToCamelCase(s string) string {
re, _ := regexp.Compile(`[-_]\w`)
res := re.ReplaceAllStringFunc(s, func(m string) string {
return strings.ToUpper(m[1:])
})
return res
}
func main() {
s := "the-stealth-warrior"
fmt.Println(ToCamelCase(s))
}
See the Go playground.
The output is theStealthWarrior
.
The [-_]\w
pattern matches a -
or _
and then any word char. If you want to exclude _
from \w
, use [^\W_]
instead of \w
.