Find most used rune in txt.file

I am new to Go, and I am currently working on a project where I have to create a program which does the following:

  • Count the number of lines with text in a txt. file.
  • Count the five most used runes in the same txt. file.
  • Write the result to a new txt. file.

I am new to Go, and unsure how to grasp these tasks. Does anyone have any tips on how I could do so? Most preferably with some lines of code to demonstrate.

Start searching how to open a text file. Then, you can choose which approach it is appropiate for your case. I mean read the file line by line or read all lines in a string or an slice.

Hello, I think by using a map data type could make implementation easier but with loss of speed

func main() {

	f, err := os.Open(TXTFILE)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	defer f.Close()

	reader := bufio.NewReader(f)

	rc := 0
	for {
		s, err := reader.ReadString('\n')
		rc++
		if err == io.EOF {
			break
		}
		fmt.Print(graspRune(s))
	}
}

func graspRune(input string) map[rune]int {

    runes := make(map[rune]int)

    for _, val := range input {
        runes[val]++
    }

    return runes
}

Thank you all. I will read the articles! The map solution sounds like my best plan as per now

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.