如何在C++中按表情符號拆分字符串 [英] How to split a string by emojis in C++

查看:0
本文介紹了如何在C++中按表情符號拆分字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試獲取一串表情符號,并將它們拆分成每個表情符號的向量

給定字符串:

std::string emojis = "????????????????";

我正在嘗試獲?。?/p>

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數據了解不多,但我正在嘗試弄清楚如何檢查emoji數據的開始和結束時間,以便能夠將字符串拆分到每個emoji

推薦答案

我絕對建議您使用具有更好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字符串,每個字符串包含一個代碼點。確定字符是否為emoji表情符號作為練習:utf-8-對任何4字節字符進行解碼,并查看它們是否在正確的范圍內。

這篇關于如何在C++中按表情符號拆分字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
全免费A级毛片免费看无码播放