本文主要是介绍常见的编码格式包括 UTF-8、ASCII、ISO-8859-1、GBK转换方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
常见的编码格式包括 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 mainimport ("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.Readerif 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)
}
这篇关于常见的编码格式包括 UTF-8、ASCII、ISO-8859-1、GBK转换方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!