0
点赞
收藏
分享

微信扫一扫

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



举报

相关推荐

0 条评论