C++加密字符串变量时如何忽略空格及非字母特殊符号
解决方法
核心逻辑是新增小写字母校验,过滤非字母字符,同时单独统计有效字母的位置保证偏移规则生效,具体修改如下:
问题根源
原代码调用alphabet.find()查找字符时,遇到空格、问号这类不在a-z范围内的字符会返回string::npos(通常值为-1),直接输出就会出现无效数值。
修改步骤
- 引入
<cctype>头文件,调用islower()方法判断当前字符是否为小写字母,非字母字符直接跳过循环不处理 - 新增单独的
valid_idx变量统计有效字母的序号,不要用原字符串的下标i做偏移判断,避免跳过非字母后偏移位置错位 - 补全你定义的三个偏移量的对应逻辑,原代码仅实现了第1/4/7...位的偏移,这里补全第2/5/8...位加
second_int、第3/6/9...位加third_int的逻辑(如果不需要可以自行删除)
修改后完整代码
#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string alphabet; int encrypted_code; int first_int = 1, second_int = 2, third_int = 3; string text = "hey what is your name?"; // 有效字母计数,用于判断偏移规则 int valid_idx = 0; for (char ch = 'a'; ch <= 'z'; ch++) { alphabet += ch; } for (int i = 0; i < text.length(); i++) { char current = text[i]; // 仅处理小写字母,其余字符直接跳过 if (!islower(current)) { continue; } encrypted_code = alphabet.find(current); // 按有效字母的位置匹配偏移规则 if (valid_idx % 3 == 0) { encrypted_code += first_int; } else if (valid_idx % 3 == 1) { encrypted_code += second_int; } else { encrypted_code += third_int; } cout << encrypted_code << " "; // 有效字母计数+1 valid_idx++; } return 0; }
修改后运行会自动跳过空格、问号等非字母字符,仅输出字母加密后的数值。如果需要支持大写字母,可以先调用tolower()把字符转成小写再处理即可。
内容的提问来源于stack exchange,提问作者Peter Hwang。
相关产品推荐
相关产品推荐

