您的位置:首页 > 娱乐 > 八卦 > C++ 字符串处理5-手机号邮箱如何脱敏处理

C++ 字符串处理5-手机号邮箱如何脱敏处理

2025/2/26 4:44:22 来源:https://blog.csdn.net/luoweifu/article/details/139702855  浏览:    关键词:C++ 字符串处理5-手机号邮箱如何脱敏处理
  • 1. 关键词
  • 2. strutil.h
  • 3. strutil.cpp
  • 4. 测试代码
  • 5. 运行结果
  • 6. 源码地址

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位,中间×不超过6auto 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。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com