【程序员必知必会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);
  }
}
相关推荐
ncj3934379061 分钟前
vscode中对node项目进行断点调试
vscode·node.js
github_czy15 分钟前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
liulilittle15 分钟前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
许愿与你永世安宁1 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子1 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
ruanjiananquan991 小时前
c,c++语言的栈内存、堆内存及任意读写内存
java·c语言·c++
满分观察网友z1 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法
持梦远方2 小时前
C 语言基础入门:基本数据类型与运算符详解
c语言·开发语言·c++
YuTaoShao2 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
Heartoxx2 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法