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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章