半角輸入與全角的相互轉化

後端校驗
//全角空格爲12288,半角空格爲32
//其他字符半角(33-126)與考試.大提示全角(65281-65374)的對應關係是:均相差65248
/**
 * 全角轉化半角
 * @param input
 * @return
 */
public static String toSemiangle(String input) {
    char c[] = input.toCharArray();
    for (int i = 0; i < c.length; i++) {
        if (c[i] == '\u3000') {
            c[i] = ' ';
        }
          else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
            c[i] = (char) (c[i] - 65248);
        }
    }
    return new String(c);
}

/**
 * 半角轉全角
 * @param input
 * @return
 */
public static String zhuanQuanJiao(String input){
    char c[] = input.toCharArray();
    for ( int i=0; i<c.length;i++ ) {
        if (c[i] ==' ') {
            c[i] = '\u3000';
        }
        else if (c[i]<'\177') {
            c[i]= (char) (c[i]+65248);
        }
    }
    return new String(c);
}


有時由於用戶的原因導致數據庫的數據與當前輸入狀態不統一造成的錯誤,引發用戶對系統的質疑,所以我們在處理數據的要有一個統一的標準來使我們的系統更加穩定,一般情況下都是全角轉半角。

前端校驗

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
p{float: left;}
</style>
</head>
<body>
<p id="p1"></p>
<p>=>|轉化半角後|=></p>
<p id="p2"></p>
</body>
</html>
<script type="text/javascript">
var str = "12345";
function toSemiangle(s){
var result = '';
for (i=0 ; i<s.length; i++){
code = s.charCodeAt(i);//獲取當前字符的unicode編碼
if (code >= 65281 && code <= 65373)//在這個unicode編碼範圍中的是所有的英文字母已經各種字符
{
result += String.fromCharCode(s.charCodeAt(i) - 65248);//把全角字符的unicode編碼轉換爲對應半角字符的unicode碼
}else if (code == 12288)//空格
{
result += String.fromCharCode(s.charCodeAt(i) - 12288 + 32);
}else
{
result += s.charAt(i);
}
}
return result;
}
document.getElementById('p1').innerHTML = str;
document.getElementById('p2').innerHTML = toSemiangle(str);
</script>

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