使用Java函数实现字符编码和解码。
发布时间:2023-07-04 17:13:27
字符编码和解码是将字符转换为对应的编码值,或者将编码值转换为对应的字符。
在Java中,可以使用以下方法实现字符编码和解码:
1. 字符编码:使用getBytes()方法将字符转换为字节数组,然后通过指定的字符集将字节数组转换为编码值。
public static String encode(String str, String charset) {
try {
byte[] bytes = str.getBytes(charset);
StringBuilder encoded = new StringBuilder();
for (byte b : bytes) {
encoded.append((int) b).append(",");
}
return encoded.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
示例使用:
String input = "abc"; String charset = "UTF-8"; String encoded = encode(input, charset); System.out.println(encoded); // 输出:97,98,99
2. 字符解码:使用String的构造函数将编码值转换为字节数组,然后通过指定的字符集将字节数组转换为字符。
public static String decode(String encoded, String charset) {
String[] bytesStr = encoded.split(",");
byte[] bytes = new byte[bytesStr.length];
for (int i = 0; i < bytesStr.length; i++) {
bytes[i] = (byte) Integer.parseInt(bytesStr[i]);
}
try {
return new String(bytes, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
示例使用:
String input = "97,98,99"; String charset = "UTF-8"; String decoded = decode(input, charset); System.out.println(decoded); // 输出:abc
以上代码示例使用UTF-8字符集进行编码和解码,你也可以根据需求修改字符集。注意,在实际使用中,编码和解码的字符集应该保持一致,否则可能导致乱码或转换失败。
