1. 程式人生 > 實用技巧 >Java String字串和Unicode字串相互轉換程式碼(包括混油普通字元的Unicode)

Java String字串和Unicode字串相互轉換程式碼(包括混油普通字元的Unicode)

Java String字串和Unicode字串相互轉換程式碼(包括混油普通字元的Unicode)

網上大部分有關“Java String字串和Unicode字元相互轉換程式碼”的博文幾乎都僅是將全為Unicode字元的字串進行轉換,而我們日常很可能需要的是將混有普通字元的Unicode一併轉換(例如“\u0061\u0062\u0063(123)”,我們希望轉換成“abc(123)”,而實際上網上的通用方法並不符合該需求,執行即報錯),普通字元跳過而Unicode字元要進行轉換,在進行字串的查詢替換擷取什麼的使用正則表示式往往是個很好的選擇。

因此作者我結合了網上提供的方法結合正則i表示式實現該需求!

在進行程式碼講解時我先貼出實現程式碼:

網上一般實現程式碼:

字串轉換unicode java方法程式碼片段:

    /**
	 * 字串轉換unicode
	 * @param string
	 * @return
	 */
	public static String string2Unicode(String string) {
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < string.length(); i++) {
			// 取出每一個字元
			char c = string.charAt(i);
			// 轉換為unicode
			unicode.append("\\u" + Integer.toHexString(c));
		}
 
		return unicode.toString();
	}

unicode轉換字串java方法程式碼片段:

	/**
	 * unicode 轉字串
	 * @param unicode 全為 Unicode 的字串
	 * @return
	 */
	public static String unicode2String(String unicode) {
		StringBuffer string = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
 
		for (int i = 1; i < hex.length; i++) {
			// 轉換出每一個程式碼點
			int data = Integer.parseInt(hex[i], 16);
			// 追加成string
			string.append((char) data);
		}
 
		return string.toString();
	}

結合正則實現的程式碼:

混有普通字元的Unicode轉換為字串:

	/**
	 * 含有unicode 的字串轉一般字串
	 * @param unicodeStr 混有 Unicode 的字串
	 * @return
	 */
	public static String unicodeStr2String(String unicodeStr) {
		int length = unicodeStr.length();
		int count = 0;
		//正則匹配條件,可匹配“\\u”1到4位,一般是4位可直接使用 String regex = "\\\\u[a-f0-9A-F]{4}";
		String regex = "\\\\u[a-f0-9A-F]{1,4}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(unicodeStr);
		StringBuffer sb = new StringBuffer();
		
		while(matcher.find()) {
			String oldChar = matcher.group();//原本的Unicode字元
			String newChar = unicode2String(oldChar);//轉換為普通字元
			// int index = unicodeStr.indexOf(oldChar);
            // 在遇見重複出現的unicode程式碼的時候會造成從源字串獲取非unicode編碼字元的時候擷取索引越界等
			int index = matcher.start();
 
			sb.append(unicodeStr.substring(count, index));//新增前面不是unicode的字元
			sb.append(newChar);//新增轉換後的字元
			count = index+oldChar.length();//統計下標移動的位置
		}
		sb.append(unicodeStr.substring(count, length));//新增末尾不是Unicode的字元
		return sb.toString();
	}

完整程式碼:

package util;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 
 * <p>Title: String 與 Unicode 互相轉換的工具類</p>
 * <p>Description: </p>
 * <p>Company: SCAU@Copyright</p>
 * @Copyright 1.0
 * @author jodenhe ([email protected])
 * @version 1.0
 * @since 2017年8月17日 下午9:42:50
 */
public class StringUnicodeUtil {
	
	/**
	 * 含有unicode 的字串轉一般字串
	 * @param unicodeStr 混有 Unicode 的字串
	 * @return
	 */
	public static String unicodeStr2String(String unicodeStr) {
		int length = unicodeStr.length();
		int count = 0;
		//正則匹配條件,可匹配“\\u”1到4位,一般是4位可直接使用 String regex = "\\\\u[a-f0-9A-F]{4}";
		String regex = "\\\\u[a-f0-9A-F]{1,4}";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(unicodeStr);
		StringBuffer sb = new StringBuffer();
		
		while(matcher.find()) {
			String oldChar = matcher.group();//原本的Unicode字元
			String newChar = unicode2String(oldChar);//轉換為普通字元
			// int index = unicodeStr.indexOf(oldChar);
            // 在遇見重複出現的unicode程式碼的時候會造成從源字串獲取非unicode編碼字元的時候擷取索引越界等
			int index = matcher.start();
			
			sb.append(unicodeStr.substring(count, index));//新增前面不是unicode的字元
			sb.append(newChar);//新增轉換後的字元
			count = index+oldChar.length();//統計下標移動的位置
		}
		sb.append(unicodeStr.substring(count, length));//新增末尾不是Unicode的字元
		return sb.toString();
	}
	
	/**
	 * 字串轉換unicode
	 * @param string
	 * @return
	 */
	public static String string2Unicode(String string) {
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < string.length(); i++) {
			// 取出每一個字元
			char c = string.charAt(i);
			// 轉換為unicode
			unicode.append("\\u" + Integer.toHexString(c));
		}
 
		return unicode.toString();
	}
 
	/**
	 * unicode 轉字串
	 * @param unicode 全為 Unicode 的字串
	 * @return
	 */
	public static String unicode2String(String unicode) {
		StringBuffer string = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
 
		for (int i = 1; i < hex.length; i++) {
			// 轉換出每一個程式碼點
			int data = Integer.parseInt(hex[i], 16);
			// 追加成string
			string.append((char) data);
		}
 
		return string.toString();
	}
	
	public static void main(String[] args) {
		String str = "abc";
		String str2 = string2Unicode(str);
		System.out.println(str2);
		System.out.println(unicodeStr2String(str2));
		System.out.println(unicodeStr2String("\\u61HJ\\u62\\u63(sfkfdsl)"));
	}
}

程式碼執行結果圖:

重要程式碼講解:

程式碼的實現其實很簡單,因此只對核心主要程式碼進行講解,如對程式碼有疑惑可私信或留下評論!

1、正則匹配規則:

String regex = "\\\\u[a-f0-9A-F]{1,4}";

這個是正則匹配的規則,可能你會疑惑為什麼使用“\\u”來匹配javan字串的“\u”,原因很簡單,因為這樣才匹配得上嘛(開個玩笑)直接看測試圖1-2

測試圖1:

測試圖2:

很明顯在菜鳥上使用兩種匹配方式匹配到的結果是不同的,而java字串需要轉義,上圖的“\u”java就應該是“\u”,因此就要使用“\\u”來進行匹配!

[a-f0-9A-F]{1,4}

”[a-f0-9A-F]“ :這個意思就是a到f,0到9,A到F出現的數都符合要求,“{1,4}”意思是前面的字元出現1到4個(其實一般的Unicode都是“\u”後面家4個字元的,如“\u0061”代表“a”,因此該式子可改為“\\u[a-f0-9A-F]{4}”,這樣可能更符合實際要求)

轉發自https://blog.csdn.net/JodenHe/article/details/77343197