I have string like this ClientLovesProcess
I need to add a space between each uppercase letter except for the first uppercase letter so the end result would be this Client Loves Process
I don't think golang has the best string support but this is how I was thinking about going about it:
First loop through each letter so something like this:
name := "ClientLovesProcess"
wordLength := len(name)
for i := 0; i < wordLength; i++ {
letter := string([]rune(name)[i])
// then in here I would like to check
// if the letter is upper or lowercase
if letter == uppercase{
// then break the string and add a space
}
}
The issue is I don't know how to check if a letter is lower or uppercase in go. I checked the strings manual but they don't some to have a function for it. What would be another approach to get this done with go?
The function you're looking for is unicode.IsUpper(r rune) bool
.
I would use a bytes.Buffer
so that you're not doing a bunch of string concatenations, which results in extra unnecessary allocations.
Here's an implementation:
func addSpace(s string) string {
buf := &bytes.Buffer{}
for i, rune := range s {
if unicode.IsUpper(rune) && i > 0 {
buf.WriteRune(' ')
}
buf.WriteRune(rune)
}
return buf.String()
}
And a play link.
You can test for upper case with the unicode package. This is my solution:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
name := "ClientLovesProcess"
newName := ""
for _, c := range name {
if unicode.IsUpper(c){
newName += " "
}
newName += string(c)
}
newName = strings.TrimSpace(newName) // get rid of space on edges.
fmt.Println(newName)
}