小石头
Excellence in any department can be attained only by the labor of a lifetime; it is not to be purchased at a lesser price.
posts - 91,comments - 22,trackbacks - 0

关于全角转半角的问题,在Unicode中,标点、数字、字母的半角编码最高位均为0,它们的全角编码与半角编码的第三位相差32h。

public class Test
{
 public static void main(String [] args)
 {
  String QJstr="HELLO";
  String QJstr1="HELLO";
    
     String result=BQchange(QJstr);
     String result1=QBchange(QJstr1);
   
      System.out.println(QJstr+"\n"+result);
      System.out.println(QJstr1+"\n"+result1);


 }

//半角转全角
  public static final String BQchange(String QJstr)
  {
      String outStr="";
     String Tstr="";
     byte[] b=null;

      for(int i=0;i<QJstr.length();i++)
      {    
        try
        {
          Tstr=QJstr.substring(i,i+1);
          b=Tstr.getBytes("unicode");
        }
        catch(java.io.UnsupportedEncodingException e)
        {
          e.printStackTrace();
        }    
  
       if (b[3] !=-1)
       {
         b[2]=(byte)(b[2]-32);
         b[3]=-1;
         try
         {      
           outStr=outStr+new String(b,"unicode");
         }
         catch(java.io.UnsupportedEncodingException e)
         {
          e.printStackTrace();
         }     
       }
       else outStr=outStr+Tstr;
     }
   
     return outStr;
  }
 

//全角转半角
  public static final String QBchange(String QJstr)
  {
     String outStr="";
     String Tstr="";
     byte[] b=null;

     for(int i=0;i<QJstr.length();i++)
     {    
       try
       {
         Tstr=QJstr.substring(i,i+1);
         b=Tstr.getBytes("unicode");
       }
       catch(java.io.UnsupportedEncodingException e)
       {
         e.printStackTrace();
       }    
  
       if (b[3] ==-1)
       {
         b[2]=(byte)(b[2]+32);
         b[3]=0;
        try
        {      
         outStr=outStr+new String(b,"unicode");
        }
        catch(java.io.UnsupportedEncodingException e)
        {
         e.printStackTrace();
        }     
       }
       else outStr=outStr+Tstr;
     }
   
     return outStr;
  }

}

输出结果为:

HELLO
HELLO
HELLO
HELLO

 


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=496423

 

posted on 2007-01-16 23:10 小石头 阅读(605) 评论(0)  编辑  收藏 所属分类: 我的java学习

只有注册用户登录后才能发表评论。


网站导航: