英文:
Swedish characters in Go Lang
问题
以下函数无法处理瑞典字符,即 å/Å/ä/Ä/ö/Ö。
func StartsWithUppercase(s string) bool {
    return (string(s[0]) == strings.ToUpper(string(s[0])))
}
我该如何继续检查一个字符串是否以大写的瑞典字符开头?
w := "åÅäÄöÖ"
for i := 0; i < len(w); i++ {
    fmt.Println(i, w[i])
}
结果为:
1. 195 
2. 165
3. 195
4. 133
5. 195 
6. 164
7. 195
8. 132
9. 195
10. 182 
11. 195
12. 150
英文:
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
答案1
得分: 9
索引一个string会索引它的字节,而不是它的_rune_(一个rune是一个Unicode码点)。
你想要做的是检查string的第一个字符(rune),而不是它的UTF-8编码形式中的第一个字节。标准库中有支持这个操作的函数:unicode.IsUpper()。
要获取第一个rune,你可以将string转换为rune切片,并取第一个元素(索引为0)。
ins := []string{
	"å/Å/ä/Ä/ö/Ö",
	"Å/ä/Ä/ö/Ö"}
for _, s := range ins {
	fmt.Println(s, unicode.IsUpper([]rune(s)[0]))
}
输出:
å/Å/ä/Ä/ö/Ö false
Å/ä/Ä/ö/Ö true
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论