Golang. Number of letters in a sentence


Calculate the number of characters in the text – how many which letter occurs how many times. You can do this with maps, but there is another, C-style way: character arithmetic:

package main

import "fmt"

const AZ = 'z' - 'a' + 1 // 26

func main() {
	s := "lets calculate how much times each letter presented in sentance"

	var counter [AZ]int

	for _, a := range s {
		if a >= 'a' && a <= 'z' {
			counter[a-'a']++
		}
	}

	for i := 0; i < AZ; i++ {
		fmt.Printf("%c: %d \n", i+'a', counter[i])
	}
}

With an additional if, you can modify this code to also take uppercase letters into account:

package main

import "fmt"

const AZ = 'z' - 'a' + 1 // 26

func main() {
	s := "Lets calculate how much times each letter presented in sentance"

	var counter [AZ]int

	for _, a := range s {
		if a >= 'a' && a <= 'z' {
			counter[a-'a']++
		} else if a >= 'A' && a <= 'Z' {
			counter[a-'A']++
		}
	}

	for i := 0; i < AZ; i++ {
		fmt.Printf("%c: %d \n", i+'a', counter[i])
	}
}

And one more variant with different cycle:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func getInput(r *bufio.Reader) string {
	input, _ := r.ReadString('\n')

	input = strings.TrimSpace(input)

	input = strings.ToLower(input)

	return input
}

func main() {
	r := bufio.NewReader(os.Stdin)

	line := getInput(r)

	var az [26]int

	// 97 a

	for _, v := range line {
		if v >= 'a' && v <= 'z' {
			az[v-97]++
		}
	}

	for i, v := range az {
		if v != 0 {
			fmt.Printf("%c - %d\n", i+97, v)
		}
	}

}

And one more way – with using of “maps” (just for an exercise):

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strings"
)

func getInput(r *bufio.Reader) string {
	input, _ := r.ReadString('\n')

	return strings.ToLower(strings.TrimSpace(input))
}

func main() {
	r := bufio.NewReader(os.Stdin)

	line := getInput(r)

	// 97 a... lets make it with maps

	az := map[rune]int{}
	var keys []int // for sorting

	for _, v := range line {
		if v >= 'a' && v <= 'z' {
			az[v] += 1
		}
	}

	for v := range az {
		keys = append(keys, int(v))
	}

	sort.Ints(keys)

	for _, v := range keys {
		fmt.Printf("%c - %d\n", v, az[rune(v)])
	}

}

 


This entry was posted in Go (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.