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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.