关闭

unicode字符和String类型相互转换

标签: stringnullimportclassc
1249人阅读 评论(0) 收藏 举报
分类:

import java.util.*;
public class unicodetostring
{
public static void main(String[] args)
 {
  
        //for(int i= 0;i<args.length;i++)
  //{
       //    String stu = StringToUnicode(args[i]);
  //   System.out.println(" "+stu+" ");
  
  // }
  
  for(int i= 0;i<args.length;i++)
  {
           String stu = UnicodeToString(args[i]);
     System.out.println(" "+stu+" ");
  
   }
}
/**
     *    Stringtounicode
     *
     * @param asString
     * @return
     */
    public static final String StringToUnicode(String asString) {
        char[] ac = asString.toCharArray();
        int iValue;
        String s = null;
        StringBuffer sb = new StringBuffer();
        for (int ndx = 0; ndx < ac.length; ndx++) {
            iValue = ac[ndx];
            if (iValue < 0x10) {
                s = "//u000";
            } else if (iValue < 0x100) {
                s = "//u00";
            } else if (iValue < 0x1000) {
                s = "//u0";
            } else {
                s = "//u";
            }
            sb.append(s + Integer.toHexString(iValue));
        }
        return sb.toString();
    }

    /**
     *   unicodetoString
     *
     * @param s
     * @return
     */
    public static final String UnicodeToString(String s) {
     if (s==null||"".equalsIgnoreCase(s.trim())) return "";
        StringBuffer sb = new StringBuffer();
        boolean escape = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
            case '//':
            case '%': 
                escape = true;
                break;
            case 'u':
            case 'U':
                if (escape) {
                    try {
                        sb.append((char) Integer.parseInt(s.substring(i + 1,
                                i + 5), 16));
                        escape = false;
                    } catch (NumberFormatException e) {
                        throw new IllegalArgumentException();
                    }
                    i += 4;
                } else {
                    sb.append(c);
                }
                break;
            default:
                sb.append(c);
                break;
            }
        }
        return sb.toString();
    }
 }
  

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:238750次
    • 积分:1754
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:21篇
    • 译文:0篇
    • 评论:47条
    最新评论
    哥们儿