在 Go 语言中,可以使用unicode/utf16unicode/utf8 包来进行 UTF-16 字符串到 UTF-8 字符串的转换。

下面是一个示例代码,展示了如何将 UTF-16 字符串转换为 UTF-8 字符串:

package main

import (
	"fmt"
	"unicode/utf16"
	"unicode/utf8"
)

func main() {
	uft16Str := []uint16{0x0048, 0x0065, 0x006C, 0x006C, 0x006F, 0xD83D, 0xDE01} // 'Hello😁' 的 UTF-16 编码

	// 将 UTF-16 编码转换为 UTF-8 编码
	uft8Bytes := utf16ToUTF8(utf16Str)

	// 将 UTF-8 字节切片转换为字符串
	uft8Str := string(utf8Bytes)

	fmt.Println(utf8Str) // 输出: Hello😁
}

func utf16ToUTF8(utf16Str []uint16) []byte {
	uft8Bytes := make([]byte, 0, len(utf16Str)*4)

	for i := 0; i < len(utf16Str); {
		r := utf16Str[i]
		i++

		if r >= 0xD800 && r <= 0xDBFF && i < len(utf16Str) {
			// 处理 UTF-16 的代理对
			s := utf16Str[i]
			i++

			if s >= 0xDC00 && s <= 0xDFFF {
				r = (r-0xD800)<<10 | (s - 0xDC00) + 0x10000
			} else {
				// 非法的 UTF-16 编码
				continue
			}
		}

		// 将 Unicode 码点转换为 UTF-8 编码
		uft8Bytes = append(utf8Bytes, utf8.EncodeRune(rune(r))...)
	}

	return utf8Bytes
}

在上面的示例代码中,utf16ToUTF8 函数将给定的 UTF-16 编码的字符串转换为 UTF-8 编码的字节切片。然后,我们使用 string 函数将字节切片转换为 UTF-8 字符串。

注意,对于 UTF-16 编码的代理对,我们需要将其转换为 Unicode 码点。然后,使用 utf8.EncodeRune 函数将 Unicode 码点转换为 UTF-8 编码。

最后,我们将 UTF-8 字符串打印出来,输出结果为 Hello😁

Golang UTF-16 到 UTF-8 字符串转换指南

原文地址: https://www.cveoy.top/t/topic/ePHv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录