簡體   English   中英

如何在 c 中修復 printf 使用 UTF8 和 %10s 管理字符串的方式?

[英]how can I fix the way printf manage strings with UTF8 and %10s, in c?

我正在嘗試使用 c 和 printf 打印一個帶有非 ASCII 字符的字符串,這是程序:

include <stdio.h>
void main(void){
  printf("<0123456789> BOTH %s\n","<%5s>");
  printf("<%5s>\n"," w ");
  printf("<%5s>\n"," δ ");
}

我得到

<0123456789> BOTH <%5s>
<   w >
<  δ >

所以字符串的大小有問題。 如何獲得相同大小的兩個字符串?

要使用 unicode,您應該使用fwprintf而不是printf

另見7.24.2 格式化寬字符輸入/輸出函數

您的小寫 delta 字符不是 8 位值。 它由兩個字節表示,因此使用寬度說明符 5 打印它會導致它僅在 4 個可見空間中打印。 您可以在其他希臘字母中看到同樣的問題。

您可以通過打印strlen(" δ ")的結果來進一步了解這一點,該結果打印4

好的,我找到了一種計算字符串打印字符數的方法。 還有更簡單的......

#define ONEMASK ((size_t)(-1) / 0xFF)
#include <stdint.h>
static size_t
cp_strlen_utf8(const char * _s){
//http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html

const char * s;
size_t count = 0;
size_t u;
unsigned char b;

/* Handle any initial misaligned bytes. */
for (s = _s; (uintptr_t)(s) & (sizeof(size_t) - 1); s++) {
    b = *s;

    /* Exit if we hit a zero byte. */
    if (b == '\0')
        goto done;

    /* Is this byte NOT the first byte of a character? */
    count += (b >> 7) & ((~b) >> 6);
}

/* Handle complete blocks. */
for (; ; s += sizeof(size_t)) {
    /* Prefetch 256 bytes ahead. */
    __builtin_prefetch(&s[256], 0, 0);

    /* Grab 4 or 8 bytes of UTF-8 data. */
    u = *(size_t *)(s);

    /* Exit the loop if there are any zero bytes. */
    if ((u - ONEMASK) & (~u) & (ONEMASK * 0x80))
        break;

    /* Count bytes which are NOT the first byte of a character. */
    u = ((u & (ONEMASK * 0x80)) >> 7) & ((~u) >> 6);
    count += (u * ONEMASK) >> ((sizeof(size_t) - 1) * 8);
}

/* Take care of any left-over bytes. */
for (; ; s++) {
    b = *s;

    /* Exit if we hit a zero byte. */
    if (b == '\0')
        break;

    /* Is this byte NOT the first byte of a character? */
    count += (b >> 7) & ((~b) >> 6);
}

done:
    return ((s - _s) - count);
}

使用這些函數,我可以打印互補的空格數以對齊下一個表格單元格。

函數 printf() 不計算正確打印的字符。 也許 printf() 必須修復。

我不知道這些是通用解決方案,還是僅適用於我現在使用的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM