← 中文资源

简体中文版本

unicode.IsGraphic 与 IsPrint 分类

unicode.IsGraphic 覆盖字母、数字、符号与全部 Zs 空格类,IsPrint 只把 ASCII 空格算作空格;两者对 NBSP/全角空格的判定差异用一组 rune 样本直接对照。

阅读英文原文

实现说明

unicode.IsGraphic 与 IsPrint 分类的核心是函数 main。 在这里做循环的是 for _, r := range samples。

使用要点

  • 演示输出是带标签的(U+、space graphic:、nbsp graphic:),每个操作都会留下自己的一行标注。

常见问题

运行「unicode.IsGraphic 与 IsPrint 分类」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 U+、space graphic:、nbsp graphic: 这类标签。

核心语句

for _, r := range "name=ada\x1b[0m" {
	if unicode.IsGraphic(r) {
		visible = append(visible, r)
	}
}
fmt.Println("visible only:", string(visible))
}
for _, r := range samples {
	fmt.Printf("U+%04X graphic=%-5t print=%-5t letter=%t\n",
		r, unicode.IsGraphic(r), unicode.IsPrint(r), unicode.IsLetter(r))
}

代码示例

package main

import (
	"fmt"
	"unicode"
)

func main() {
	samples := []rune{
		'A', '中', 'Ω', '3', '·', // 字母/数字/符号
		' ',                        // ASCII 空格
		0x00A0,                     // NBSP:Latin-1 不换行空格
		0x3000,                     // 全角空格
		'\t', '\n', 0x0007,        // 控制字符
	}

	for _, r := range samples {
		fmt.Printf("U+%04X graphic=%-5t print=%-5t letter=%t\n",
			r, unicode.IsGraphic(r), unicode.IsPrint(r), unicode.IsLetter(r))
	}

	// 文档化的唯一差别在空格:IsPrint 只收 ASCII 空格(U+0020),
	// IsGraphic 收全部 Zs 空格类(NBSP、全角空格等)
	space := rune(' ')
	nbsp := rune(0x00A0)
	fmt.Println("space graphic:", unicode.IsGraphic(space), "print:", unicode.IsPrint(space))
	fmt.Println("nbsp graphic:", unicode.IsGraphic(nbsp), "print:", unicode.IsPrint(nbsp))

	// 过滤输入里的不可见字符:保留 IsGraphic,丢掉其余
	var visible []rune
	for _, r := range "name=ada\x1b[0m" {
		if unicode.IsGraphic(r) {
			visible = append(visible, r)
		}
	}
	fmt.Println("visible only:", string(visible))
}