AzLearn

تمرين إعادة البناء

String Stats

أعد كتابة برنامج Go يحسب إحصاءات قصيرة عن نص.

go ~12 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
package main

import (
	"fmt"
	"strings"
	"unicode"
)

type Stats struct {
	Characters int
	Words      int
	Letters    int
	Digits     int
	Spaces     int
}

func measure(text string) Stats {
	stats := Stats{
		Characters: len([]rune(text)),
		Words:      len(strings.Fields(text)),
	}

	for _, r := range text {
		switch {
		case unicode.IsLetter(r):
			stats.Letters++
		case unicode.IsDigit(r):
			stats.Digits++
		case unicode.IsSpace(r):
			stats.Spaces++
		}
	}

	return stats
}

func main() {
	text := "Go 1.22 makes small tools feel fast."
	stats := measure(text)

	fmt.Println(text)
	fmt.Printf("characters: %d\n", stats.Characters)
	fmt.Printf("words:      %d\n", stats.Words)
	fmt.Printf("letters:    %d\n", stats.Letters)
	fmt.Printf("digits:     %d\n", stats.Digits)
	fmt.Printf("spaces:     %d\n", stats.Spaces)
}
اكتب هنا