【程序员必知必会2】中英文混合超长字符串如何截断(C++)

背景

用户输入的搜索关键词可能是包含中英文、特殊字符混合的字符串,如果长度超长,可能会导致下游服务的报错,需要提前对keyword做截断。

版本一 (只考虑中英文)

cpp 复制代码
bool CutOff(std::string keyword){
      
   int query_length = keyword.length();
  
   // 空结果直接返回
   if(keyword == 0){
       LOG(WARNING) <<"bad query, the length of query is zero";
   return false;
   }

   auto query_max_length=Config::GetMaxKeywordQueryLength()*3;
	// 超过最大长度截断 注:一个汉字长度为3
    if (query_length > query_max_length) {
      const char* query = keyword.c_str();
      int end = 0;
      while (end < query_max_length && end < strlen(query)) {
        int one_word = ((unsigned int)query[end] > 0x80) ? 3 : 1;
        if (end + one_word <= query_max_length) {
          end += one_word;
        } else {
           break;
        }
      }
      keyword = keyword.substr(0, end);
   }
}

版本二(考虑所有字符)

上线后发现请求下游rpc服务时会有INTERNAL错误。原因是keyword中可能包含特殊字符,只按照3字节和1字节的方式取有可能出现将一个字符截取一半,出现乱码的情况。

为了覆盖所有的字符类型,需要了解UTF-8的特点。

  1. UTF-8是一种变长字节编码方式。 对于某一个字符的UTF-8编码,如果只有一个字节则其最高二进制位为0;
  2. 如果是多字节,其第一个字节从最高位开始,连续的二进制位值为1的个数决定了其编码的位数,其余各字节均以10开头。
  3. UTF-8最多可用到6个字节。

读取每个字符的时候需要根据其首位字节的大小,确定该字符占用了多少字节,再往后取多少字节。

cpp 复制代码
bool CutOff(std::string keyword) {
  int query_length = keyword.length();
  // 空结果直接返回
  if (query_length == 0) {
    LOG(WARNING) << "bad query, the length of query is zero";
    return false;
  }

  auto query_max_length = 300;

  // 超过最大长度,截断
  if (query_length > query_max_length) {
    const char* query = search_context->query.c_str();
    int end = 0;
    int one_word = 0;
    while (end < query_max_length && end < strlen(query)) {
      unsigned char str = (unsigned int)query[end];
      if (str >= 252) {  // 六个字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
        one_word = 6;
      } else if (str >= 248) {  // 五个字节 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
        one_word = 5;
      } else if (str >= 240) {  // 四个字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
        one_word = 4;
      } else if (str >= 224) {  // 三字节 1110xxxx 10xxxxxx 10xxxxxx
        one_word = 3;
      } else if (str >= 192) {  // 两字节 110xxxxx 10xxxxxx
        one_word = 2;
      } else {  // 单字节 0xxxxxxx
        one_word = 1;
      }

      if (end + one_word <= query_max_length) {
        end += one_word;
      } else {
        break;
      }
    }
    keyword = keyword.substr(0, end);
  }
}
相关推荐
米糕闯编程18 分钟前
鱼香ros2(五)用C++编写节点
c++·ros2·cmakelists·鱼香
深圳满意度咨询1 小时前
医院满意度数字化测评系统:从数据采集到智能决策的技术实践
算法
xiangyun612 小时前
【408数据结构 08】队列:循环队列判空判满,408年年考,一次讲清
c语言·开发语言·数据结构·c++·算法
xiangyun612 小时前
【408数据结构 06】双链表、循环链表、静态链表
c语言·开发语言·数据结构·c++·算法
OKkankan3 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
蓝速科技3 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发
302wanger3 小时前
推荐下我的两个AI信息源
算法
索尔~古德曼4 小时前
CF——错题的集合
算法
fpcc4 小时前
计算机原理—构建过程中的分段分析
c++
xxwxx__4 小时前
C++ AVL 树深度剖析:平衡二叉搜索树原理、源码与面试考点
数据结构·c++