你可以使用Go语言如何在字符串中找到带重音的字母呢?

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

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 &quot;fmt&quot;
    
    func main() {
    	word := &quot;c&#232;&#242;&#224;i&quot;
    	letter := &quot;&#232;&quot;
    	var counter int
    
    	for i := 0; i &lt; len(word); i++ {
    		if string(word[i]) == letter {
    			counter++
    		}
    	}
    	fmt.Print(counter)
    }


     
I imagine this error is due to some encoding problem but can&#39;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 (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func main() {
	word := &quot;c&#232;&#242;&#224;i&quot;
	letter := &quot;&#232;&quot;
	letterOccurences := strings.Count(word, letter)
	fmt.Printf(&quot;No. of occurences of \&quot;%s\&quot; in \&quot;%s\&quot;: %d\n&quot;, letter, word, letterOccurences)
}

Output:

No. of occurences of &quot;&#232;&quot; in &quot;c&#232;&#242;&#224;i&quot;: 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++
}
}

https://go.dev/play/p/wZOIEedf-ee

huangapple
  • 本文由 发表于 2022年7月6日 05:27:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/72875721.html
匿名

发表评论

匿名网友

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

确定