Java字符串全半角转换

       虽然生活中很少用到全角,但是有时还是会用到对字符串进行全半角的转换,尤其是全角转换为半角,在这里简单记录一下,以备以后使用参考:

/**
 * 字符串全半角转换 
 */
package com.project.util;
import java.io.UnsupportedEncodingException;
/**
 * @author admin
 * @category 字符串全半角转换
 */
public class CommonUtil {
   
 /**
  * 全角转半角的
  * @param fullStr 全角字符串
  * @return halfStr 半角字符串
  */
 public static final String switchFullToHalf(String fullStr){
  if(fullStr == null){
   return "";
  }
  StringBuffer buffer = new StringBuffer("");
  try{
   String singleStr = "";
   byte[] byteArray = null;
   for (int i = 0; i < fullStr.length(); i++) {
    singleStr = fullStr.substring(i, i + 1);
    // 全角空格转换成半角空格
    if (singleStr.equals(" ")) {
     buffer.append(" ");
     continue;
    }
    byteArray = singleStr.getBytes("unicode");
    // 得到 unicode 字节数据
    if (byteArray[2] == -1) {// 表示全角
     byteArray[3] = (byte) (byteArray[3] + 32);
     byteArray[2] = 0;
     buffer.append(new String(byteArray, "unicode"));
    } else {
     buffer.append(singleStr);
    }
   }
  }catch(UnsupportedEncodingException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }
  return buffer.toString();
 }
 
 /**
  * 半角转全角
  * @param halfStr半角字符串
  * @return fullStr 全角字符串
  */
 public static final String switchHalfToFull(String halfStr){
  if(halfStr == null){
   return "";
  }
  StringBuffer buffer = new StringBuffer("");
  try{
   String singleStr = "";
   byte[] byteArray = null;
   for (int i = 0; i < halfStr.length(); i++) {
    singleStr = halfStr.substring(i, i + 1);
    if (singleStr.equals(" ")) {// 半角空格转为全角空格
     buffer.append(" ");
     continue;
    }
    byteArray = singleStr.getBytes("unicode");
    if (byteArray[2] == 0) {// 表示半角
     byteArray[3] = (byte) (byteArray[3] - 32);
     byteArray[2] = -1;
     buffer.append(new String(byteArray, "unicode"));
    } else {
     buffer.append(singleStr);
    }
   }
  }catch(UnsupportedEncodingException e){
   e.printStackTrace();
  }catch(Exception e){
   e.printStackTrace();
  }
  return buffer.toString();
 }
}

 

你可能感兴趣的:(全角半角转换)