Java計算における英語の長さのいくつかの方法


プロジェクト開発ではしばしば入力文字のチェック、特に中国語と英語を混ぜたチェックに触れます。検証の需要を満たすために、中国語と英語の長さを計算する必要がある場合があります。
本論文ではいくつかの一般的な方法によって長さの計算を行う。
<span style="font-size:18px;">import java.io.UnsupportedEncodingException;


/**
 *         
 * @author a123demi
 *
 */
public class EnChValidate {
	public static void main(String[] args){
		
		String validateStr= "     abcde  ii";
		
		int bytesStrLength = getBytesStrLength(validateStr);
		int chineseLength = getChineseLength(validateStr);
		int regexpLength = getRegExpLength(validateStr);
		System.out.println("getBytesLength:" + bytesStrLength + ",chineseLength:" + chineseLength + 
				",regexpLength:" + regexpLength);
		
	}
	
	/**
	 *                     
	 * @param validateStr
	 * @return
	 */
	public static int getBytesStrLength(String validateStr){
		String tempStr = "";
		try {
			tempStr = new String(validateStr.getBytes("gb2312"),"iso-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempStr.length();
	}
	
	/**
     *         ,     ,         2 
     *
     * @param validateStr
     *                  
     * @return       
     */
    public static int getChineseLength(String validateStr) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /*         ,       ,          2,   1 */
        for (int i = 0; i < validateStr.length(); i++) {
            /*        */
            String temp = validateStr.substring(i, i + 1);
            /*           */
            if (temp.matches(chinese)) {
                /*        2 */
                valueLength += 2;
            } else {
                /*        1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }
    
    /**
     *                  "**"
     *             : [\u4e00-\u9fa5]
     *        (      ):[^\x00-\xff]
     * @param validateStr
     * @return
     */
    public static int getRegExpLength(String validateStr){
//    	String temp = validateStr.replaceAll("[\u4e00-\u9fa5]", "**");
    	String temp = validateStr.replaceAll("[^\\x00-\\xff]", "**");
    	return temp.length();
    }
}
</span>