Swedish characters in Go Lang

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 get to checking if a string begins with a uppercase 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 
+5
source share
1 answer

Indexing a string indexes its bytes, not its runes (a rune is the unicode code number).

What you want to do is check the first character ( rune ) string , and not its first byte in UTF-8 encoded form. And for this there is support in the standard library: unicode.IsUpper() .

To get the first rune , you can convert string to a piece of runes and transfer the first element (with index 0).

 ins := []string{ "å/Å/ä/Ä/ö/Ö", "Å/ä/Ä/ö/Ö"} for _, s := range ins { fmt.Println(s, unicode.IsUpper([]rune(s)[0])) } 

Conclusion:

 å/Å/ä/Ä/ö/Ö false Å/ä/Ä/ö/Ö true 
+9
source

Source: https://habr.com/ru/post/1214165/


All Articles