The following function does not work with Swedish characters, i.e å/Å/ä/Ä/ö/Ö
.
func StartsWithUppercase(s string) bool {
return (string(s[0]) == strings.ToUpper(string(s[0])))
}
How do I proceed to check if a string starts with upper case Swedish character?
w := "åÅäÄöÖ"
for i := 0; i < len(w); i++ {
fmt.Println(i, w[i])
}
Results in:
1. 195
2. 165
3. 195
4. 133
5. 195
6. 164
7. 195
8. 132
9. 195
10. 182
11. 195
12. 150
Indexing a string
indexes its bytes not its runes (a rune
is a unicode codepoint).
What you want to do is check the first character (rune
) of the string
, not its first byte in its UTF-8 encoded form. And for this there is support in the standard library: unicode.IsUpper()
.
To get the first rune
, you can convert the string
to a slice of runes, and take the first element (at index 0).
ins := []string{
"å/Å/ä/Ä/ö/Ö",
"Å/ä/Ä/ö/Ö"}
for _, s := range ins {
fmt.Println(s, unicode.IsUpper([]rune(s)[0]))
}
Output:
å/Å/ä/Ä/ö/Ö false
Å/ä/Ä/ö/Ö true