【问题标题】:Printing every character of a UTF8 string打印 UTF8 字符串的每个字符
【发布时间】:2016-10-29 13:19:48
【问题描述】:

我对字符串的 Unicode/UTF8 表示不熟悉。我正在尝试读取UTF8 编码文件,用空格分隔,然后打印每个单词中的每个字符/代码点(用空格分隔)。

我能够使用wchar_t(我知道它在内部使用utf16utf32(?))从文件中读取文本、打印文本并将其写入另一个文件。但是,我无法使用wchar_t 来获取子字符串或逐个元素地遍历它。

为了解决这个问题,我使用了 IBM 的 ICU 库。代码:

while (fgetws(readString, 1000, wifile) != NULL) {
        wprintf(L"String: %s\n", readString);
        //split string on the base of spaces.
        wchar_t *nextToken = NULL;
        wchar_t *token = wcstok_s(readString, L" ", &nextToken);
        UChar *utf8Token = (UChar *)token;
        u_printf("Token in UChar: %S\n", utf8Token);
        while (token != NULL) {
            printf("Hello.\n");
            fwprintf(wofileString, L"%ls and length: %d\n", token, wcslen(token));
            fwprintf(wofileString, L"UTF8 rep:%s and length: %d\n", utf8Token, u_strlen(utf8Token));
            int32_t counter = 0;
            for (counter = 0; counter < u_strlen(utf8Token);) {
                UChar32 ch;
                U8_NEXT(utf8Token, counter, u_strlen(utf8Token), ch);
                fwprintf(wofileString, L"Token[%d] = ", counter);
                if (ch < 127) {
                    printf("Less than 127.\n");
                    if (ch > 1) {
                        printf("Printing%d.\n", ch);
                        u_fprintf((UFILE *)wofileString, "%c\n", (UChar)ch);
                    }
                } else if (ch == CharacterIterator::DONE) {
                    printf("Done.\n");
                    u_fprintf((UFILE *)wofileString, "[CharacterIterator::DONE]\n");
                } else {
                    printf("More than 127.\n");
                    u_fprintf((UFILE *)wofileString, "[%X]\n", ch);
                }
            }
            token = wcstok_s(NULL, L" ", &nextToken);
            utf8Token = (UChar *)token;
            counter = 0;
        }
        fputws(L"Complete String: ", wofileString);
        fputws(readString, wofileString);
        fputws(L"\n", wofileString);
    }

该程序在到达打印字符的部分时总是停止工作。

我的问题:
1. 如何打印输入的 UTF8 字符串中的所有“字符”?
2. 转换:UChar *utf8Token = (UChar *) token; 是否正确?鉴于token 的内部表示是UTF16UTF32?
3. 我哪里错了?
4. 如何获取字符串的子串?

【问题讨论】:

  • 您确定您的代码停止了吗?也许,你的终端无法显示 UTF。
  • @Matthias:是的。我确信它会停止。 Windows 让您知道它已停止。控制台无法显示 UTF,但会显示奇怪的符号和字符。

标签: c string utf-8 icu


【解决方案1】:

fwprintf(wofileString,… u_fprintf((UFILE *)wofileString,…

这两行之一是错误的,具体取决于 wofileString 实际是什么。

我建议只使用 u_… 函数。

事实上,我只是使用u_printf("string", …)u_printf_u(L"String", …) 而不是fwprintffputws

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-01
    • 2012-09-11
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2011-09-28
    相关资源
    最近更新 更多