Go语言中的瑞典字符

huangapple go评论77阅读模式
英文:

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 &#229;/&#197;/&#228;/&#196;/&#246;/&#214;.

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 := &quot;&#229;&#197;&#228;&#196;&#246;&#214;&quot;
for i := 0; i &lt; 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{
	&quot;&#229;/&#197;/&#228;/&#196;/&#246;/&#214;&quot;,
	&quot;&#197;/&#228;/&#196;/&#246;/&#214;&quot;}

for _, s := range ins {
	fmt.Println(s, unicode.IsUpper([]rune(s)[0]))
}

Output:

&#229;/&#197;/&#228;/&#196;/&#246;/&#214; false
&#197;/&#228;/&#196;/&#246;/&#214; true

huangapple
  • 本文由 发表于 2015年2月25日 20:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/28719523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定