c++ - 如何在 C++ 中通过表情符号分割字符串
问题描述
我正在尝试获取一串表情符号并将它们拆分为每个表情符号的向量
给定字符串:
std::string emojis = "";
我试图得到:
std::vector<std::string> splitted_emojis = {"", "", "", "", "", "", "", ""};
编辑
我试过这样做:
std::string emojis = "";
std::vector<std::string> splitted_emojis;
size_t pos = 0;
std::string token;
while ((pos = emojis.find("")) != std::string::npos)
{
token = emojis.substr(0, pos);
splitted_emojis.push_back(token);
emojis.erase(0, pos);
}
但它似乎terminate called after throwing an instance of 'std::bad_alloc'
在几秒钟后抛出。
当尝试使用以下方法检查字符串中有多少表情符号时:
std::string emojis = "";
std::cout << emojis.size() << std::endl; // returns 32
它返回一个更大的数字,我假设它是 unicode 数据。我对 unicode 数据了解不多,但我试图弄清楚如何检查表情符号的数据何时开始和结束,以便能够将字符串拆分为每个表情符号
解决方案
我肯定会建议您使用具有更好 unicode 支持的库(所有大型框架都支持),但在紧要关头,您可以知道 UTF-8 编码将 Unicode 字符分布在多个字节上,并且第一个字节确定一个字符由多少个字节组成。
我从boost偷了一个函数。split_by_codepoint 函数对输入字符串使用迭代器,并使用前 N 个字节(其中 N 由字节计数函数确定)构造一个新字符串,并将其推送到 ret 向量。
// Taken from boost internals
inline unsigned utf8_byte_count(uint8_t c)
{
// if the most significant bit with a zero in it is in position
// 8-N then there are N bytes in this UTF-8 sequence:
uint8_t mask = 0x80u;
unsigned result = 0;
while(c & mask)
{
++result;
mask >>= 1;
}
return (result == 0) ? 1 : ((result > 4) ? 4 : result);
}
std::vector<std::string> split_by_codepoint(std::string input) {
std::vector<std::string> ret;
auto it = input.cbegin();
while (it != input.cend()) {
uint8_t count = utf8_byte_count(*it);
ret.emplace_back(std::string{it, it+count});
it += count;
}
return ret;
}
int main() {
std::string emojis = u8"";
auto split = split_by_codepoint(emojis);
std::cout << split.size() << std::endl;
}
请注意,此函数只是将字符串拆分为 UTF-8 字符串,每个字符串包含一个代码点。确定字符是否为表情符号作为练习:UTF-8 解码任何 4 字节字符并查看它们是否在正确的范围内。
推荐阅读
- python - 从 url 获取文本返回空数据框
- python - 如何在 django 中加载经过训练的模型
- asp.net-core - 将对象(和子对象)从 Razor 页面发送到另一个页面
- cookies - Cookie 在生产 NextJS getServerSideProps 中未定义
- java - 如何在多个 Json Schema 文件中使用 $id 和 $ref
- ios - 如何查看蓝牙状态?
- sql - Hiveql - 在 select 语句中具有多个 where 条件的百分位数
- jakarta-ee - 如何在 jakarta EE9 的计时器中实现拦截器
- couchdb - 当我试图在 couchdb 中创建用户时,它给了我错误 {"error":"forbidden","reason":"Doc ID must be of the form org.couchdb.user:name"}
- java - 无法模拟服务帐户来创建日历事件