KK asked in 電腦與網際網路程式設計 · 1 decade ago

unicode to string in Java

String mystr = new String("\u4e94");

System.out.println(mystr);

will print "五".

But when I try to change the unicode dynamaticlly:

public void transferToUnicode(num){

String mystr = new String("\\u" + Integer.toHexString(num));

System.out.println(mystr);}

Will print "\u4E94".

How should I do to let the second case to print out ""?

Thanks a lot!

Update:

不好意思,是我沒寫清楚;我是希望在第二個例子中印出的結果仍為"五"而非"\u4E94".

我是希望能有一個API,傳入unicode之後能印出中文字.

Thanks!

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    好像快懂了~但最後這句看不懂

    How should I do to let the second case to print out ""?

    你問題是在說什麼?

    是要下面這樣嗎?

    public void transferToUnicode(String num){

    String mystr = new String("\\u" + Integer.toHexString((int)num));

    System.out.println(mystr);

    }

    2009-04-29 12:55:08 補充:

    import java.util.*;

    public class unicode2GB{

    public static void main(String arg[]){

    String test = unicodeToGB("\\u4e94\\u4e94");

    System.out.println(test);

    }

    2009-04-29 12:55:45 補充:

    private static String unicodeToGB(String s){

    StringBuffer sb = new StringBuffer();

    StringTokenizer st = new StringTokenizer(s,"\\u");

    while (st.hasMoreTokens()){

    sb.append((char)Integer.parseInt(st.nextToken(), 16));

    }

    return sb.toString();

    }

    }

    2009-04-29 12:56:10 補充:

    請把ans2接著ans1後面

    Source(s): me, ans1, ans2, me
Still have questions? Get your answers by asking now.