Register / Login  |  Desktop view  |  Jump to bottom of page

網頁程式設計 Web Development » 如何只將Big5不支援的UTF-8碼轉為HTML Entity

Author: andowson, 七段學員
2011-05-20 15:19:24
有些資料庫使用Big5編碼,遇到Big5字集外的UTF-8中文字元時,可以採用將該字元轉換為&#xxxxx;格式,再跟原字串合併儲存,例如當字串變數str="中文喆堃"時,後面兩個中文字不在Big5字集的範圍內,我們希望將其轉為
"中文喆堃"這樣子的結果。

底下是範例程式
UTF8ToBig5.java:
package com.andowson.chinese;


import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class UTF8ToBig5 {

public static String convertHtml(String str) {
StringBuilder buf = new StringBuilder(str.length());
CharsetEncoder enc = Charset.forName("Big5").newEncoder();
for (int idx = 0; idx < str.length(); idx++) {
char ch = str.charAt(idx);
if (enc.canEncode(ch)) {
buf.append(ch);
} else {
buf.append("&#").append((int)ch).append(';');
}
}
return buf.toString();
}

/**
* @param args
*/
public static void main(String[] args) {
String str = "中文喆堃";
String result = convertHtml(str);
System.out.println(result);
}

}


參考資料:
http://stackoverflow.com/questions/1760766/how-to-convert-non-supported-character-to-html-entity-in-java

Filename UTF8ToBig5.java
Description UTF8ToBig5.java
Filesize 736 bytes
Downloaded 6 time(s)
[Disk] Download





Register / Login  |  Desktop view  |  Jump to top of page