arrays - 使用标准库将 char 转换为 wchar_t?

标签 arrays c type-conversion windows-1252 widestring

我有一个需要 wchar_t 数组作为参数的函数。我不知道标准库函数可以将 char 转换为 wchar_t,所以我编写了一个快速的脏函数,但我想要一个没有错误和未定义行为的可靠解决方案。标准库是否有进行此转换的函数?

我的代码:

wchar_t *ctow(const char *buf, wchar_t *output)
{
    const char ANSI_arr[]    =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<.>/? \t\n\r\f";
    const wchar_t WIDE_arr[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<.>/? \t\n\r\f";

    size_t n = 0, len = strlen(ANSI_arr);

    while (*buf) {
        for (size_t x = 0; x < len; x++) {
            if (*buf == ANSI_arr[x]) {
                output[n++] = WIDE_arr[x];
                break;
            }
        }
        buf++;
    }
    output[n] = L'\0';
    return output;
}

最佳答案

嗯,转换函数在 stdlib.h (*) 中声明。但您必须知道,对于 latin1 aka ISO-8859-1 字符集中的任何字符,转换为宽字符只是一个赋值,因为低于 256 的 unicode 代码的字符是 latin1 字符。

因此,如果您的初始字符集是 ISO-8859-1,则转换很简单:

wchar_t *ctow(const char *buf, wchar_t *output) {
 wchar_t cr = output;
    while (*buf) {
        *output++ = *buf++;
    }
    *output = 0;
    return cr;
}

假设调用者传递了一个指向大小足以存储所有转换字符的数组的指针。

如果您使用任何其他字符集,则必须使用众所周知的库,例如 icu ,或者手动构建一个,这对于单字节字符集(ISO-8859-x 系列)来说很简单,对于多字节字符集(如 UTF8)则更复杂。

但是在不知道您希望能够处理的字符集的情况下,我无法说更多......

顺便说一句,普通的 ascii 是 ISO-8859-1 字符集的子集。

(*) 来自cplusplus.com

int mbtowc (wchar_t* pwc, const char* pmb, size_t max);

Convert multibyte sequence to wide character The multibyte character pointed by pmb is converted to a value of type wchar_t and stored at the location pointed by pwc. The function returns the length in bytes of the multibyte character.

mbtowc has its own internal shift state, which is altered as necessary only by calls to this function. A call to the function with a null pointer as pmb resets the state (and returns whether multibyte characters are state-dependent).

The behavior of this function depends on the LC_CTYPE category of the selected C locale.

关于arrays - 使用标准库将 char 转换为 wchar_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38174773/

相关文章:

javascript - 为什么一个只有一个数字的数组在 Javascript 中是一个数字?

javascript - 使用变量对多维数组进行排序

c - 使用 GDB 检查 C 指针

c++ - 避免双数舍入

sql - PostgreSQL 将带有逗号分隔的整数的字符串拆分为逗号分隔的整数

arrays - 如何一次从用户窗体添加多个数据行到 Excel 数据库

html - Angular,使用服务在数组中显示数组

使用 2 种欧几里德方法寻找 GCD 的复杂性

c - 这个二维 DCT 代码实际上是如何工作的?

flutter - 类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型转换中类型 'Map<String, String>' 的子类型