1. 程式人生 > >把帶中文的字串轉為 /u16進位制 的 Unicode 碼

把帶中文的字串轉為 /u16進位制 的 Unicode 碼

話不多說直接上程式碼:

/**
	 * 帶中文的字串轉為  /u16進位制 的  Unicode 碼
	 */
	private String tfToHex(String str){
		Integer.toHexString(0);
		//匹配單字元是否中文的正則
		String regex = "[\u4e00-\u9fa5]";
		char [] arr = str.toCharArray();
		StringBuffer newStr = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			char c = arr[i];
			if ((c+"").matches(regex)) {
				String temp = Integer.toHexString(c);
				newStr.append("\\u"+temp);
			}else {
				newStr.append(c);
			}
		}
		return newStr.toString();
	}

測試程式碼:

public static void main(String[] args) {
		System.out.println(new Test2().tfToHex("歡迎檢視胡蕭徒的-CSDN"));
	}

輸出結果:

\u6b22\u8fce\u67e5\u770b\u80e1\u8427\u5f92\u7684-CSDN