首頁 > 後端開發 > Golang > 如何在Windows控制台中正確顯示UTF-8字串?

如何在Windows控制台中正確顯示UTF-8字串?

DDD
發布: 2024-11-02 21:55:30
原創
677 人瀏覽過

How to Display UTF-8 Strings Correctly in Windows Consoles?

編碼UTF-8 字串以在Windows 控制台中顯示

在Windows 控制台中執行Go 執行檔時,可能會出現帶有特殊字元的字串由於控制台的預設IBM850 編碼而損壞。以下是如何確保字串正確編碼和顯示:

解決方案:

利用kernel32.dll 庫中的WriteConsoleW 函數寫入寬字元(UTF-16) ) 繞過預設編碼,直接將字串輸出到控制台。

實作:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<code class="go">import (

    "syscall"

    "unicode/utf16"

    "unsafe"

)

 

// Declare the WriteConsoleW function

var procWriteConsoleW = syscall.NewLazyDLL("kernel32.dll").NewProc("WriteConsoleW")

 

// Define a function to print a UTF-8 string to the console

func consolePrintString(strUtf8 string) {

    // Convert the UTF-8 string to UTF-16

    strUtf16 := utf16.Encode([]rune(strUtf8))

 

    // Write the UTF-16 string to the console

    syscall.Syscall6(procWriteConsoleW.Addr(), 5,

        uintptr(syscall.Stdout),

        uintptr(unsafe.Pointer(&strUtf16[0])),

        uintptr(len(strUtf16)),

        uintptr(unsafe.Pointer(nil)),

        uintptr(0),

        0)

}</code>

登入後複製

範例:

1

2

3

4

5

6

7

8

<code class="go">package main

 

import "fmt"

 

func main() {

    consolePrintString("Hello ☺\n")

    consolePrintString("éèïöîôùòèìë\n")

}</code>

登入後複製

這種方法繞過了控制台的預設方法編碼,確保帶有特殊字元的字串能夠正確顯示。請注意,它是 Windows 特定的,並且涉及使用未記錄的方法。

以上是如何在Windows控制台中正確顯示UTF-8字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板