今天在使用一个【手机号码归属地api】的时候,返回值里中文是Unicode格式,样子是这样的:
- "province":"\u9ed1\u9f99\u6c5f","city":"\u7261\u4e39\u6c5f"
第一种方法很丑:
- /**
- * 这个方法乍一看我尼玛太丑了,可是比下面的方法 好用!
- *
- * @param theString
- * @return
- */
- public static String decodeUnicode(String theString) {
- char aChar;
- int len = theString.length();
- StringBuffer outBuffer = new StringBuffer(len);
- for (int x = 0; x < len; ) {
- aChar = theString.charAt(x++);
- if (aChar == '\\') {
- aChar = theString.charAt(x++);
- if (aChar == 'u') {
- // Read the xxxx
- int value = 0;
- for (int i = 0; i < 4; i++) {
- aChar = theString.charAt(x++);
- switch (aChar) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- value = (value << 4) + aChar - '0';
- break;
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':
- value = (value << 4) + 10 + aChar - 'a';
- break;
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':
- value = (value << 4) + 10 + aChar - 'A';
- break;
- default:
- throw new IllegalArgumentException(
- "Malformed \\uxxxx encoding.");
- }
- }
- outBuffer.append((char) value);
- } else {
- if (aChar == 't')
- aChar = '\t';
- else if (aChar == 'r')
- aChar = '\r';
- else if (aChar == 'n')
- aChar = '\n';
- else if (aChar == 'f')
- aChar = '\f';
- outBuffer.append(aChar);
- }
- } else
- outBuffer.append(aChar);
- }
- return outBuffer.toString();
- }
第二种方法很好看:
- /**
- * 这个方法,看着爽,效率低(时间长,耗内存)
- *
- * @param text
- * @return
- */
- public static String unicode2Utf8(String text) {
- try {
- byte[] converttoBytes = text.getBytes("UTF-8");
- String s2 = new String(converttoBytes, "UTF-8");
- return s2;
- } catch (Exception e) {
- e.printStackTrace();
- return e.getMessage();
- }
- }
说下我的理由吧,写了一段测试方法:
- private void test(){
- String text = "\u5e7f\u5c9b\u4e4b\u604b.mp3";
- long beginTime1 = System.currentTimeMillis() ;
- Log.i("方法一", "开始");
- for (double i=0; i<25000;i++){
- Util.decodeUnicode(text);
- }
- Log.i("方法一", "共耗时:"+(System.currentTimeMillis()-beginTime1));
- long beginTime2 = System.currentTimeMillis() ;
- Log.i("方法二", "开始");
- for (double i=0; i<25000;i++){
- Util.unicode2Utf8(text);
- }
- Log.i("方法二", "共耗时:" + (System.currentTimeMillis() - beginTime2));
- }
我们每种方法跑25000次,并且打印了两种方法的耗时,我们来看结果:
方法二不仅耗时长,而且进行了4次GC。结果不言而喻吧。 Way One Win !!