欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用java代码判断一个字符串里是否包含中文字符

程序员文章站 2022-06-19 11:00:31
...

测试代码:

package unicode;

import org.apache.commons.lang3.StringUtils;



public class ChineseTest {

	public static void main(String[] args) {
		ChineseTest tool = new ChineseTest();
		System.out.println(tool.containsChineseCharacter("Helloab!?12D#asDSF!&#$"));
		System.out.println(tool.containsChineseCharacter("你好	"));

	}
	
	protected boolean containsChineseCharacter(final String s)
	{
		if (StringUtils.isNotEmpty(s))
		{
			for (int i = 0; i < s.length();)
			{
				final int codepoint = s.codePointAt(i);
				System.out.println("Code Point: " + codepoint);
				i += Character.charCount(codepoint);
				System.out.println("i: " + i + " CharCount: " + Character.charCount(codepoint));
				if (Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN)
				{
					return true;
				}
			}
		}
		return false;
	}

}

输出:

Code Point: 72
i: 1 CharCount: 1
Code Point: 101
i: 2 CharCount: 1
Code Point: 108
i: 3 CharCount: 1
Code Point: 108
i: 4 CharCount: 1
Code Point: 111
i: 5 CharCount: 1
Code Point: 97
i: 6 CharCount: 1
Code Point: 98
i: 7 CharCount: 1
Code Point: 33
i: 8 CharCount: 1
Code Point: 63
i: 9 CharCount: 1
Code Point: 49
i: 10 CharCount: 1
Code Point: 50
i: 11 CharCount: 1
Code Point: 68
i: 12 CharCount: 1
Code Point: 35
i: 13 CharCount: 1
Code Point: 97
i: 14 CharCount: 1
Code Point: 115
i: 15 CharCount: 1
Code Point: 68
i: 16 CharCount: 1
Code Point: 83
i: 17 CharCount: 1
Code Point: 70
i: 18 CharCount: 1
Code Point: 33
i: 19 CharCount: 1
Code Point: 38
i: 20 CharCount: 1
Code Point: 35
i: 21 CharCount: 1
Code Point: 36
i: 22 CharCount: 1
false
Code Point: 20320
i: 1 CharCount: 1
true