我如何使用GO中的字符串中找到重音字母?

发布于 2025-02-13 05:09:08 字数 483 浏览 0 评论 0原文

给定一个代表一个单词的字符串 var word ,而代表字母的字符串 var字母,我如何计算单词中的重音字母的数量?

如果 var字母是一个非重音单词,我的代码有效,但是当字母重音或任何特殊字符时, 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)
}


 

我想象此错误是由于一些编码问题,但不能完全掌握我需要研究的内容。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2025-02-20 05:09:08

如何利用 strings。 count

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)
}

输出:

No. of occurences of "è" in "cèòài": 1

How about utilizing strings.Count:

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
伪装你 2025-02-20 05:09:08

正如@jimb所暗示的那样,字符串中的字母(又称符文)可能不是完全匹配的字节:

在其单个符文上迭代字符串:

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文