英文:
How can I find accented letters in a string using go?
问题
给定一个表示单词的字符串 var word,和一个表示字母的字符串 var letter,我该如何计算单词中重音字母的数量?
如果 var letter 是非重音字母,我的代码可以正常工作,但是当字母是重音字母或任何特殊字符时,var counter 打印出的数字是0。
package main
import "fmt"
func main() {
word := "cèòài"
letter := "è"
var counter int
for i := 0; i < len(word); i++ {
if string(word[i]) == letter {
counter++
}
}
fmt.Print(counter)
}
我想这个错误可能是由于某种编码问题造成的,但我还不太明白我需要查找什么。
<details>
<summary>英文:</summary>
### Given a string *var word* that represents a word, and a string *var letter* that represents a letter, how do I count the number of accented letters in the word? ###
If *var letter* is a non-accented word, my code works, but when the letter is accented or any special character, *var counter* prints the number 0.
package main
import "fmt"
func main() {
word := "cèòài"
letter := "è"
var counter int
for i := 0; i < len(word); i++ {
if string(word[i]) == letter {
counter++
}
}
fmt.Print(counter)
}
I imagine this error is due to some encoding problem but can't quite grasp what I need to look into.
</details>
# 答案1
**得分**: 0
如何利用`strings.Count`函数来实现:
```go
package main
import (
"fmt"
"strings"
)
func main() {
word := "cèòài"
letter := "è"
letterOccurences := strings.Count(word, letter)
fmt.Printf("在\"%s\"中出现\"%s\"的次数:%d\n", word, letter, letterOccurences)
}
输出结果:
在"cèòài"中出现"è"的次数:1
英文:
How about utilizing <code>strings.<b>Count</b></code>:
package main
import (
"fmt"
"strings"
)
func main() {
word := "cèòài"
letter := "è"
letterOccurences := strings.Count(word, letter)
fmt.Printf("No. of occurences of \"%s\" in \"%s\": %d\n", letter, word, letterOccurences)
}
Output:
No. of occurences of "è" in "cèòài": 1
答案2
得分: 0
如@JimB所暗示的,字符串中的字母(也称为符文)可能不会完全匹配字节偏移量:
要遍历字符串的每个符文:
for pos, l := range word {
_ = pos // 字节位置,例如第3个符文可能在字节位置6,因为有多字节符文
if string(l) == letter {
counter++
}
}
https://go.dev/play/p/wZOIEedf-ee
英文:
As @JimB alluded to, letters (aka runes) in a string may not be at exactly matching byte-offsets:
To iterate a string over its individual runes:
for pos, l := range word {
_ = pos // byte position e.g. 3rd rune may be at byte-position 6 because of multi-byte runes
if string(l) == letter {
counter++
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论