黑马程序员:字符的编码和解码(输入中文查看他的Unicode码)

本文介绍了一个简单的Java程序,用于演示如何处理控制台输入的中文字符串,并实现不同字符集之间的转换,如从ISO-8859-1解码后再用GB2312重新编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import com.sun.corba.se.impl.oa.toa.TOA;


public class CharDeCode {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //System.getProperties().list(System.out);
     System.setProperty("file.encoding","iso8859-1");
 System.out.print("please enter a chinese String:");
  int ch=0;
  byte[] buf=new byte[1024];
  int  pos=0;
  String str =null;
    while(true)
   {
     try
     {
          ch=System.in.read();
          System.out.println(Integer.toHexString(ch));
          switch(ch)
          {
             case '/r':           
              break;
             case '/n':
               str=new String(buf,0,pos,"gb2312"); //switch 里不能定义变量
                 /*gb2312 可不写 因为我们的缺省字符集 就是GB2312*/
               for(int i=0;i<str.length();i++)
               {
                System.out.println(Integer.toHexString(
                  str.charAt(i)));
             /*如果我们得到一个GB2312却被iso8859-1解码的String
              * 我们可以将它编码还原为字节数组,在解码成GB2312 如下:       
              *System.out.print(new String((str.getBytes
              *    ("iso8859-1")),"gb2312"));
              */
                 }
                 break;
             default:
              buf[pos++]=(byte)ch;
          }
         
     }catch(Exception e)
        {
       e.printStackTrace();
        }
      }
  
  
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值