JAva共通ツールクラス-全角回転半角、半角回転全角

2314 ワード

全角回転半角、半角回転全角コード
/**
 * <PRE>
 *          ->  ,  ->    
 * codingwhy.com
 * </PRE>
 */
public class BCConvert {

	/**
	 * ASCII       !  ,     33(Decimal)
	 */
	static final char DBC_CHAR_START = 33; //   !

	/**
	 * ASCII       ~  ,     126(Decimal)
	 */
	static final char DBC_CHAR_END = 126; //   ~

	/**
	 *      ASCII       !  ,    65281
	 */
	static final char SBC_CHAR_START = 65281; //   !

	/**
	 *      ASCII       ~  ,    65374
	 */
	static final char SBC_CHAR_END = 65374; //   ~

	/**
	 * ASCII                        
	 */
	static final int CONVERT_STEP = 65248; //         

	/**
	 *       ,      ASCII     ,      
	 */
	static final char SBC_SPACE = 12288; //      12288

	/**
	 *       , ASCII  32(Decimal)
	 */
	static final char DBC_SPACE = ' '; //     

	/**
	 * <PRE>
	 *     ->        
	 *      ,! ˜     ,    
	 * </PRE>
	 */
	private static String bj2qj(String src) {
		if (src == null) {
			return src;
		}
		StringBuilder buf = new StringBuilder(src.length());
		char[] ca = src.toCharArray();
		for (int i = 0; i < ca.length; i++) {
			if (ca[i] == DBC_SPACE) { //        ,         
				buf.append(SBC_SPACE);
			} else if ((ca[i] >= DBC_CHAR_START) && (ca[i] <= DBC_CHAR_END)) { //    ! ~       
				buf.append((char) (ca[i] + CONVERT_STEP));
			} else { //       ascii                  
				buf.append(ca[i]);
			}
		}
		return buf.toString();
	}

	/**
	 * <PRE>
	 *     ->        
	 *         ,  !   ~     ,    
	 * </PRE>
	 */
	public static String qj2bj(String src) {
		if (src == null) {
			return src;
		}
		StringBuilder buf = new StringBuilder(src.length());
		char[] ca = src.toCharArray();
		for (int i = 0; i < src.length(); i++) {
			if (ca[i] >= SBC_CHAR_START && ca[i] <= SBC_CHAR_END) { //       !   ~   
				buf.append((char) (ca[i] - CONVERT_STEP));
			} else if (ca[i] == SBC_SPACE) { //        
				buf.append(DBC_SPACE);
			} else { //        ,  !   ~      
				buf.append(ca[i]);
			}
		}
		return buf.toString();
	}

	public static void main(String[] args) {
		String s = "nihao CODINGWHY|   NIhao ,。324 123 ";
		System.out.println(BCConvert.qj2bj(s));
	}
}
実行結果
nihao CODINGWHY|   NIhao ,。324 123