常见的编码格式包括 UTF-8、ASCII、ISO-8859-1、GBK转换方法
- Python 示例
- Ruby 示例
- Java 示例
- Go 示例
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 示例
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 示例
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 示例
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)
re服务器托管网turn
}
fmt.Println(convertedStr)
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: element ui 虚拟滚动 滚动到底部加载下一页
引入element ui的InfiniteScroll 无限滚动插件 div class=”news-left”> div class=”infinite-list-wrapper” style=”overflow:auto;height: 70vh”&…