文字列の実際の長さの取得

1145 ワード

public class StringUtil {
	//  
	public static int getStringLen(String s) {
		int len = 0; //  
		if (s == null || s.length() == 0) {
			len = 0; //  0
		} else {
			for (int i = 0; i < s.length(); i++) {
				char c = s.charAt(i);
				if (isChinese(c)) { //  
					len = len + 2; //  2
				} else {
					len++;//  1
				}
			}
		}
		return len;
	}

	//  Unicode 
	private static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
			return true;
		}
		return false;
	}
}