-1

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.

Logan
  • 109
  • 6
  • You are indexing individual bytes from the `word` string, but `letter` is multiple bytes itself, so they could never match. Maybe read: https://go.dev/blog/strings – JimB Jul 05 '22 at 21:32
  • 1
    What, if anything, would you like to do about decomposed vs composed accents? – torek Jul 06 '22 at 02:12

2 Answers2

0

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
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

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

colm.anseo
  • 19,337
  • 4
  • 43
  • 52