Skip to content

Latest commit

 

History

History
40 lines (36 loc) · 805 Bytes

计算字符的长度.md

File metadata and controls

40 lines (36 loc) · 805 Bytes

/**

  • 验证是否有汉字 */
	public static boolean VerifyChinese (String str) {
		
		boolean isMatche = false;
		for (int i = 0; i < str.length(); i++) {
			
			String regex = "[\u4e00-\u9fa5]{0,}$";
			isMatche = Pattern.matches(regex, ""+str.charAt(i));
			if (isMatche) {
				return isMatche;
			}
		}
		return isMatche;
	}

/**

  • 计算字符的长度,将汉字视为一位 */
	public int caculateLength (String str) {

		int chineseAmount = 0; //汉字个数计数器
		int otherAmount = 0;
		int length = 0;
		
		for (int i = 0; i < str.length(); i++) {
			boolean matches = Pattern.matches("[\u4E00-\u9FA5]{0,}$", ""+ str.charAt(i));
			if (matches) {
				chineseAmount++;
			} else {
				otherAmount ++;
			}
			length = chineseAmount + otherAmount;
		}
		return length;
	}