1. 关键词 关键词:
C++ 字符串处理 分割字符串 连接字符串 跨平台
应用场景:
有些重要信息需要保密,比如手机号、邮箱等,如何在不影响用户阅读的情况下,将这些信息脱敏处理,以保障用户的隐私安全。
2. strutil.h 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #pragma once #include <string> namespace cutl{ std::string desensitizing (const std::string &str) ; }
3. strutil.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 #include <cctype> #include <algorithm> #include "strutil.h" namespace cutl{ std::string desensitizing (const std::string &str) { std::string result; 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 ) { 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 { result = str.substr (0 , 4 ) + std::string (4 , '*' ) + str.substr (str.length () - 4 , 4 ); } return result; } }
4. 测试代码 1 2 3 4 5 6 7 8 9 10 11 12 #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. 运行结果 1 2 3 -------------------------------------------desensitizing-------------------------------------------- password: 25***74 phone: 185*****678
6. 源码地址 更多详细代码,请查看本人写的C++ 通用工具库: common_util , 本项目已开源,代码简洁,且有详细的文档和Demo。