如何使用 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)

}



 

我想这个错误是由于一些编码问题引起的,但我不太明白我需要研究什么。


杨__羊羊
浏览 104回答 2
2回答

冉冉说

如何利用:strings.Countpackage mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; word := "cèòài"&nbsp; &nbsp; letter := "è"&nbsp; &nbsp; letterOccurences := strings.Count(word, letter)&nbsp; &nbsp; fmt.Printf("No. of occurences of \"%s\" in \"%s\": %d\n", letter, word, letterOccurences)}输出:No. of occurences of "è" in "cèòài": 1

慕桂英546537

字符串中的字母(又名符文)可能与字节偏移量不完全匹配:要在其各个符文上迭代一个字符串:for pos, l := range word {&nbsp; &nbsp; _ = pos // byte position e.g. 3rd rune may be at byte-position 6 because of multi-byte runes&nbsp; &nbsp; if string(l) == letter {&nbsp; &nbsp; &nbsp; &nbsp; counter++&nbsp; &nbsp; }}https://go.dev/play/p/wZOIEedf-ee
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go