1. 关键词
关键词:
C++ 字符串处理 分割字符串 连接字符串 跨平台
应用场景:
有些重要信息需要保密,比如手机号、邮箱等,如何在不影响用户阅读的情况下,将这些信息脱敏处理,以保障用户的隐私安全。
2. strutil.h
#pragma once
#include <string>
namespace cutl
{
/**
* @brief Desensitizing a string by replacing some characters with '*'.
*
* @param str the string to be desensitized.
* @return std::string the desensitized string.
*/
std::string desensitizing(const std::string &str);
} // namespace cutl
3. strutil.cpp
#include <cctype>
#include <algorithm>
#include "strutil.h"
namespace cutl
{
// 字符串脱敏处理
std::string desensitizing(const std::string &str)
{
std::string result;
// 只打印前1/4和后1/4的内容,中间用*表示
if (str.empty())
{
result = "";
}
else if (str.length() == 1)
{
result = "*";
}
else if (str.length() == 2)
{
result = str.substr(0, 1) + std::string(str.length() - 1, '*');
}
else if (str.length() <= 6)
{
result = str.substr(0, 2) + std::string(str.length() - 2, '*');
}
else if (str.length() < 10)
{
result = str.substr(0, 2) + std::string(str.length() - 4, '*') + str.substr(str.length() - 2, 2);
}
else if (str.length() < 16)
{
// 长度控制在最长12位,中间×不超过6
auto startCount = (str.length() - 6) > 6 ? 6 : (str.length() - 6);
result = str.substr(0, 3) + std::string(startCount, '*') + str.substr(str.length() - 3, 3);
}
else
{
// 长度控制在最长12位
result = str.substr(0, 4) + std::string(4, '*') + str.substr(str.length() - 4, 4);
}
return result;
}
} // namespace cutl
4. 测试代码
#include "common.hpp"
#include "strutil.h"
void TestDesensitizing()
{
PrintSubTitle("desensitizing");
std::string password = "2515774";
std::cout << "password: " << cutl::desensitizing(password) << std::endl;
std::string phone = "18500425678";
std::cout << "phone: " << cutl::desensitizing(phone) << std::endl;
}
5. 运行结果
-------------------------------------------desensitizing--------------------------------------------
password: 25***74
phone: 185*****678
6. 源码地址
更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。