Classify Runes With The Unicode Package

Range over strings yields runes that unicode.IsLetter, IsDigit, and IsPunct classify, while strings.Map rewrites or drops each rune in one pass.

GoData Integrity

Code

gosnippet
36 lines
package main

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

func main() {
	// range 字符串按 rune 迭代:多字节字符(如中文)也是一个 rune
	input := "Go-语言-v3!"

	var letters, digits, marks []rune
	for _, r := range input {
		switch {
		case unicode.IsLetter(r):
			letters = append(letters, r)
		case unicode.IsDigit(r):
			digits = append(digits, r)
		case unicode.IsPunct(r):
			marks = append(marks, r)
		}
	}
	fmt.Println("letters:", string(letters))
	fmt.Println("digits:", string(digits))
	fmt.Println("punct:", string(marks))

	// strings.Map 对每个 rune 做变换:返回负值表示删除该字符
	cleaned := strings.Map(func(r rune) rune {
		if unicode.IsSpace(r) || unicode.IsSymbol(r) {
			return -1
		}
		return unicode.ToLower(r)
	}, "Go Dev Examples 2026!é")
	fmt.Println("mapped:", cleaned)
}

Inside the snippet

Classify Runes With The Unicode Package reduces to the function main.

Repetition is confined to for _, r := range input — the rest of the file is straight-line.

Using it

The demo output is labeled (letters:, digits:, punct:), so the printed output reads as a trace of the operations performed.

Key statements

for _, r := range input {
switch {
case unicode.IsLetter(r):
letters = append(letters, r)
case unicode.IsDigit(r):
digits = append(digits, r)
case unicode.IsPunct(r):
marks = append(marks, r)
}
}
return unicode.ToLower(r)

Interactive Tools for This Topic

FAQ

What does Classify Runes With The Unicode Package print when run?
No setup needed: run the file and look for labeled lines like `letters:`, `digits:`, `punct:` in the output.