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;
}