C++如何对vector<string>做大小写不敏感处理并统计不同字符数
所有实现依赖C++标准库的 <vector>、<string>、<cctype> 头文件,无需引入第三方库。
1. 容器内字符串统一转换为小写(大小写不敏感形式)
实现思路:遍历vector<string>中的每个字符串,对每个字符调用标准库的tolower方法转为小写,完成全容器的大小写统一处理。
#include <vector> #include <string> #include <cctype> void convertToCaseInsensitive(std::vector<std::string>& strVec) { for (auto& str : strVec) { for (auto& ch : str) { ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch))); } } }
注意:将字符强转为unsigned char后再传入tolower,是为了避免signed char类型为负值时触发未定义行为
处理效果示例:输入字符串"ABba"经过转换后会变为"abba"。
2. 统计单个字符串的不同字符总数(大小写不敏感)
实现思路:使用长度为128的布尔数组(覆盖所有ASCII字符范围)标记字符是否出现,字母统一转为小写后再标记,数字直接按原值标记,最后统计标记为true的元素总数即可。
int countDistinctChars(const std::string& str) { bool appeared[128] = {false}; int count = 0; for (unsigned char ch : str) { // 字母统一转小写后再做判断 unsigned char processedCh = std::isupper(ch) ? static_cast<unsigned char>(std::tolower(ch)) : ch; if (!appeared[processedCh]) { appeared[processedCh] = true; count++; } } return count; }
返回值示例:
- 输入
"ABba",返回值为2 - 输入
"ABba1212",返回值为4
完整测试用例
#include <iostream> int main() { // 测试功能1 std::vector<std::string> testVec = {"ABba", "ABba1212", "Test123Test"}; convertToCaseInsensitive(testVec); for (const auto& s : testVec) { std::cout << s << std::endl; } // 输出依次为:abba、abba1212、test123test // 测试功能2 std::cout << countDistinctChars("ABba") << std::endl; // 输出2 std::cout << countDistinctChars("ABba1212") << std::endl; // 输出4 return 0; }
内容的提问来源于stack exchange,提问作者math boy
相关产品推荐
相关产品推荐

