Java--字体与特殊字符

原文网址:Java--字体与特殊字符_IT利刃出鞘的博客-CSDN博客

简介

        本文介绍Java的字体与特殊字符。

非法字符

常用非法字符:

"[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t"

 例程:

package org.example.a;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
    public static void main(String[] args) {
        System.out.println(isSpecialChar("10.12"));
    }

    public static boolean isSpecialChar(String str) {
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }
}

汉字

提取汉字

法1:replaceAll

package org.example.a;

public class Demo {
    public static void main(String[] args) throws Throwable {
        String string="abcd123456中文_$,@";
        System.out.println(string.replaceAll("[^\\u4e00-\\u9fa5]", ""));
    }
}

执行结果

中文

法2:Pattern与Matcher

package org.example.a;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
    public static void main(String[] args) throws Throwable {
        Pattern pattern = Pattern.compile("[^\u4E00-\u9FA5]");
        Matcher matcher = pattern.matcher("abcd123456中文_$,@");
        System.out.println(matcher.replaceAll(""));
    }
}

执行结果

中文

判断单个汉字

package org.example.a;

public class Demo {
    public static void main(String[] args) throws Throwable {
        String string = "abcd123456中文_$,@";
        for (int index = 0; index <= string.length() - 1; index++) {
            String w = string.substring(index, index + 1);
            if (w.compareTo("\u4e00") > 0 && w.compareTo("\u9fa5") < 0) {
                System.out.println("中文的索引位置:" + index + ",值是:" + w);
            }
        }
    }
}

执行结果

中文的索引位置:10,值是:中
中文的索引位置:11,值是:文

字体

简介

Font:字体实体类

FontMetrics:用于测量字体信息

实例 

package org.example.a;

import sun.font.FontDesignMetrics;

import java.awt.*;

public class Demo {
    public static void main(String[] args) throws Throwable {
        Integer fontSize = 20;
        Font f = new Font("宋体", Font.PLAIN, fontSize);
        FontMetrics fm = FontDesignMetrics.getMetrics(f);
        Integer width = fm.stringWidth("中文a");
        System.out.println(width);
    }
}

执行结果(汉字占1个宽度,英文占半个)

50

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT利刃出鞘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值