【程序员必知必会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);
  }
}
相关推荐
乱舞八重击(junluoyu)27 分钟前
1.PagedAtteion算法
c++
2301_8035545240 分钟前
C++ 锁类型大全详解
开发语言·c++
曼巴UE51 小时前
UE5 C++ Slate 画曲线
开发语言·c++·ue5
ue星空1 小时前
UE5C++UKismetMathLibrary源代码
c++·ue5
mm-q29152227291 小时前
【天野学院5期】 第5期易语言半内存辅助培训班,主讲游戏——手游:仙剑奇侠传4,端游:神魔大陆2
人工智能·算法·游戏
minji...1 小时前
C++ 面向对象三大特性之一---多态
开发语言·c++
MoRanzhi12031 小时前
Python 实现:从数学模型到完整控制台版《2048》游戏
数据结构·python·算法·游戏·数学建模·矩阵·2048
2401_841495641 小时前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
蒙奇D索大2 小时前
【算法】递归算法实战:汉诺塔问题详解与代码实现
c语言·考研·算法·面试·改行学it
一只鱼^_2 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法