繁体   English   中英

当字符集为 ASCII 时,如何在文字字符串 ISO/ANSI C 中表示 Unicode 字符?

[英]How do I represent a Unicode character in a literal string ISO/ANSI C when the character set is ASCII?

在 Perl 中,我可以说

my $s = "r\x{e9}sum\x{e9}";

"résumé"分配给$s 我想在C中做类似的事情。具体来说,我想说

sometype_that_can_hold_utf8 c = get_utf8_char();
if (c < '\x{e9}') {
    /* do something */
}

对于 UTF8,您必须使用找到的规则自己生成编码,例如, 这里 例如,德语的尖锐 s(ß,代码点 0xdf)的 UTF8 编码为 0xc3,0x9f。 您的 e-acute(é,代码点 0xe9)的 UTF8 编码为 0xc3,0xa9。

您可以使用以下命令在字符串中放置任意十六进制字符:

char *cv = "r\xc3\xa9sum\xc3\xa9";
char *sharpS = "\xc3\x9f";

如果您有 C99 编译器,您可以使用 <wchar.h>(和 <locale.h>)并直接在源代码中输入 Unicode 代码点。

$ cat wc.c

#include <locale.h>
#include <stdio.h>
#include <wchar.h>

int main(void) {
  const wchar_t *name = L"r\u00e9sum\u00e9";
  setlocale(LC_CTYPE, "en_US.UTF-8");
  wprintf(L"name is %ls\n", name);
  return 0;
}

$ /usr/bin/gcc -std=c99 -pedantic -Wall wc.c

$ ./a.out

name is résumé

wchar_t 是您正在寻找的类型: http : //opengroup.org/onlinepubs/007908799/xsh/wchar.h.html

wchar_t setlocale()似乎是可选的

#include <stdio.h>

int main(void) {
  const char *const name = "r\u00e9sum\u00e9";
  printf("name is %s\n",name);
  return 0;
}
$ echo $LANG
en_US.UTF-8
$ /usr/bin/gcc -std=c99 -pedantic -Wall -Wextra bc.c
$ ./a.out
name is résumé

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM