gpt4 book ai didi

c++ - 如何在 C++ 中使用 UTF-8,从其他编码转换为 UTF-8

转载 作者:可可西里 更新时间:2023-11-01 18:20:18 31 4
gpt4 key购买 nike

我不知道怎么解决:

想象一下,我们有 4 个网站:

  • 答:UTF-8
  • B:ISO-8859-1
  • C: ASCII
  • D: UTF-16

我用 C++ 编写的程序执行以下操作:它下载一个网站并对其进行解析。但它必须理解内容。我的问题不是用像 ">" 这样的 ASCII 字符完成的解析或 "<" .

问题是程序应该从网站的文本中找出所有的词。单词是字母数字字符的任意组合。然后我将这些话发送到服务器。数据库和网络前端使用 UTF-8。所以我的问题是:

  • 如何将“任何”(或最常用的)字符编码转换为 UTF-8?
  • 如何在 C++ 中使用 UTF-8 字符串?我想wchar_t不起作用,因为它有 2 个字节长。 UTF-8 中的代码点最长为 4 个字节...
  • 有没有像isspace()这样的函数, isalnum() , strlen() , tolower()对于这样的 UTF-8 字符串?

请注意:我在 C++ 中不做任何输出(如 std::cout)。只是过滤出单词并将它们发送到服务器。

我知道 UTF8-CPP 但它没有 is*()功能。正如我所读,它不会从其他字符编码转换为 UTF-8。仅从 UTF-* 到 UTF-8。

编辑:我忘了说,程序必须是可移植的:Windows、Linux、...

最佳答案

How can I convert "any" (or the most used) character encoding to UTF-8?

ICU (Unicode 的国际组件)是这里的解决方案。它通常被认为是 Unicode 支持的最后发言权。就 Unicode 而言,甚至 Boost.Locale 和 Boost.Regex 也使用它。关于为什么我建议直接使用 ICU 而不是包装器(如 Boost),请参阅我对 Dory Zidon 的回答的评论。

您为给定的编码创建一个转换器...

#include <ucnv.h>

UConverter * converter;
UErrorCode err = U_ZERO_ERROR;
converter = ucnv_open( "8859-1", &err );
if ( U_SUCCESS( error ) )
{
// ...
ucnv_close( converter );
}

...然后使用 UnicodeString适当分类。

I think wchar_t does not work because it is 2 bytes long.

wchar_t 的大小是实现定义的。 AFAICR,Windows 是 2 字节(UCS-2/UTF-16,取决于 Windows 版本),Linux 是 4 字节(UTF-32)。在任何情况下,由于标准没有定义 wchar_t 的 Unicode 语义,使用它是不可移植的猜测。不要猜测,使用 ICU。

Are there functions like isspace(), isalnum(), strlen(), tolower() for such UTF-8-strings?

不是在他们的 UTF-8 编码中,但无论如何您都不会在内部使用它。 UTF-8 适合外部表示,但内部 UTF-16 或 UTF-32 是更好的选择。 Unicode 代码点(即 UChar32)确实存在上述函数;引用。 uchar.h .

Please note: I do not do any output(like std::cout) in C++. Just filtering out the words and send them to the server.

检查 BreakIterator .

Edit: I forgot to say, that the program has to be portable: Windows, Linux, ...

如果我还没有说过,一定要使用 ICU,这样可以避免很多麻烦。尽管乍一看它可能有点重量级,但它 是目前最好的实现,它 非常便携(我自己在 Windows、Linux 和 AIX 上使用它) ,并且您在未来的项目中一次又一次地使用它,因此不会浪费学习其 API 的时间。

关于c++ - 如何在 C++ 中使用 UTF-8,从其他编码转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208079/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com