【程序员必知必会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);
  }
}
相关推荐
Smile丶凉轩17 分钟前
数据库面试知识点总结
数据库·c++·mysql
Want59526 分钟前
C/C++跳动的爱心
c语言·开发语言·c++
laimaxgg32 分钟前
Qt常用控件之数字显示控件QLCDNumber
开发语言·c++·qt·qt5·qt6.3
蓝天扶光36 分钟前
c++贪心系列
开发语言·c++
IT猿手1 小时前
超多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
人工智能·算法·机器学习·matlab·无人机
Erik_LinX1 小时前
算法日记25:01背包(DFS->记忆化搜索->倒叙DP->顺序DP->空间优化)
算法·深度优先
Alidme1 小时前
cs106x-lecture14(Autumn 2017)-SPL实现
c++·学习·算法·codestepbystep·cs106x
小王努力学编程1 小时前
【算法与数据结构】单调队列
数据结构·c++·学习·算法·leetcode
最遥远的瞬间1 小时前
15-贪心算法
算法·贪心算法
万兴丶2 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#