#include #include #include

using namespace std;

vector strToUtf8(string str) { vector utf8; for (int i = 0; i < str.size(); i++) { char c = str[i]; if (c < 0x80) { utf8.push_back(c); } else if (c < 0x800) { utf8.push_back(0xc0 | (c >> 6)); utf8.push_back(0x80 | (c & 0x3f)); } else if (c < 0x10000) { utf8.push_back(0xe0 | (c >> 12)); utf8.push_back(0x80 | ((c >> 6) & 0x3f)); utf8.push_back(0x80 | (c & 0x3f)); } else { utf8.push_back(0xf0 | (c >> 18)); utf8.push_back(0x80 | ((c >> 12) & 0x3f)); utf8.push_back(0x80 | ((c >> 6) & 0x3f)); utf8.push_back(0x80 | (c & 0x3f)); } } return utf8; }

int main() { string str = "你好,世界!"; vector utf8 = strToUtf8(str); for (int i = 0; i < utf8.size(); i++) { cout << hex << utf8[i] << " "; } cout << endl; return 0;

c++ 将一个字符串转换为utf8编码的源代码

原文地址: https://www.cveoy.top/t/topic/f2Cd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录