常见的编码格式包括 UTF-8、ASCII、ISO-8859-1、GBK转换方法
- [Python 示例](#Python 示例)
- [Ruby 示例](#Ruby 示例)
- [Java 示例](#Java 示例)
- [Go 示例](#Go 示例)
Python 示例
python
def convert_encoding(input_str, from_encoding, to_encoding):
return input_str.encode(from_encoding).decode(to_encoding)
# 使用示例
converted_str = convert_encoding("你好,世界!", "utf-8", "gbk")
print(converted_str)
Ruby 示例
ruby
def convert_encoding(input_str, from_encoding, to_encoding)
input_str.encode(to_encoding, from_encoding)
end
# 使用示例
converted_str = convert_encoding("你好,世界!", "UTF-8", "GBK")
puts converted_str
Java 示例
java
public class EncodingConverter {
public static String convertEncoding(String inputStr, String fromEncoding, String toEncoding) throws UnsupportedEncodingException {
return new String(inputStr.getBytes(fromEncoding), toEncoding);
}
public static void main(String[] args) {
try {
String convertedStr = convertEncoding("你好,世界!", "UTF-8", "GBK");
System.out.println(convertedStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Go 示例
go
package main
import (
"fmt"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
"io/ioutil"
"strings"
)
func convertEncoding(inputStr, fromEncoding, toEncoding string) (string, error) {
var reader *strings.Reader
if fromEncoding == "UTF-8" && toEncoding == "GBK" {
reader = strings.NewReader(inputStr)
transformer := transform.NewReader(reader, simplifiedchinese.GBK.NewEncoder())
result, err := ioutil.ReadAll(transformer)
if err != nil {
return "", err
}
return string(result), nil
}
// 可以添加更多编码转换逻辑
return inputStr, nil
}
func main() {
convertedStr, err := convertEncoding("你好,世界!", "UTF-8", "GBK")
if err != nil {
fmt.Println("编码转换错误:", err)
return
}
fmt.Println(convertedStr)
}