Home > Net >  How can I find accented letters in a string using go?
How can I find accented letters in a string using go?

Time:07-06

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related