wonderer's program

everything will be better
posts - 19, comments - 6, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Java中的全角和半角

Posted on 2007-12-23 16:46 wonderer 阅读(1904) 评论(3)  编辑  收藏 所属分类: java
OYM中的任务中,有一项对文件内容的检查挺有意思的,就是要检查字符是否是全角的,例如“GY”(not“GY”),并且把这些字符改为半角的。
想起了在研发中心的一个朋友的抱怨:“昨天写了一整天的程序,发到广大教务处那边居然说不能用,然后亲自跑了一躺,发现不是我的程序有问题,是那边的人输入个全角字符,搜半角的字符,当然不行了”
恩,Betty写的需求真有意思,考虑的问题很周全,是一个很厉害的项目经理。如果从输入这里解决了字符是否是半角的,那么,以后的情况就容易解决很多了。恩,网上搜了一下资料,查了一下书,得出了以下代码:
public void testChar() {
  String s1 
= "123";
  String s2 
= "abc";
  String s3 
= "123abc";
  System.out.println(s1);
  System.out.println(s2);
  System.out.println(s3);
  
for (int i = 0; i < s1.length(); i++) {
   
int j = s1.charAt(i);
   
if (j > 256) {
    
int temp = j - 65248;
    
if (temp >= 0) {
     System.out.print((
char)j+"-->:" + (char) temp);
    } 
else {
      System.out.print((
char) j);
    }
   } 
else {
    System.out.print((
char) j);
   }
  }
  System.out.println();
  
  
for (int i = 0; i < s2.length(); i++) {
   
int j = s2.charAt(i);
   
if (j > 256) {
    
int temp = j - 65248;
    
if (temp >= 0) {
     System.out.print((
char)j+"-->:" + (char) temp);
    } 
else {
     System.out.print((
char) j);
    }
   } 
else {
    System.out.print ((
char) j);
   }
  }
  System.out.println();
  
  
for (int i = 0; i < s3.length(); i++) {
   
int j = s3.charAt(i);
   
if (j > 256) {
    
int temp = j - 65248;
    
if (temp >= 0) {
      System.out.print((
char)j+"-->:" + (char) temp);
    } 
else {
     System.out.print((
char) j);
    }
   } 
else {
    System.out.print((
char) j);
   }
  }
  System.out.println();
 
 }
输出的结果如下:
123
-->ab-->bc--c
123a
-->ab-->bc--c



评论

# re: Java中的全角和半角  回复  更多评论   

2007-12-23 17:12 by 黑蝙蝠
楼主注释下吧

# re: Java中的全角和半角  回复  更多评论   

2007-12-23 17:46 by beyond
全角空格为12288,半角空格为32
其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248

# re: Java中的全角和半角  回复  更多评论   

2007-12-27 23:23 by wonderer
@黑蝙蝠
只是觉得代码比较简单,所以没注释,呵呵,不过写代码还是养成好习惯的比较好。

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


网站导航: