C++ 字符串中识别取出非中文字符

2023-12-23 19:12:05

bool isChineseChar(unsigned char c) {
?? ?if ((c & 0x80) == 0) {
?? ??? ?// ASCII编码字符
?? ??? ?return false;
?? ?}
?? ?// 对于UTF-8编码中的中文字符,其第一个字节的最高位至少有三个1,例如 1110xxxx (E0-EF)
?? ?// 而对于单字节的ASCII字符,最高位是0
?? ?return true;
}

std::string extractNonChinese(const std::string& input) {
?? ?std::string result;

?? ?for (size_t i = 0; i < input.size();) {
?? ??? ?if (isChineseChar(static_cast<unsigned char>(input[i]))) {
?? ??? ??? ?// 计算UTF-8编码的中文字符字节数
?? ??? ??? ?unsigned char c = input[i];
?? ??? ??? ?int num_bytes = 0;
?? ??? ??? ?while (c & 0x80) {
?? ??? ??? ??? ?num_bytes++;
?? ??? ??? ??? ?c <<= 1;
?? ??? ??? ?}
?? ??? ??? ?i += num_bytes; ?// 跳过整个中文字符
?? ??? ?}
?? ??? ?else {
?? ??? ??? ?// 非中文字符,直接添加到结果中
?? ??? ??? ?result += input[i++];
?? ??? ?}
?? ?}

?? ?return result;
}

文章来源:https://blog.csdn.net/mfc5158/article/details/135167881
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。