c++ - 如何用相反的字母替换字符串中的每个字母?C++
问题描述
如何用相反的字母替换字符串中的每个字母?例如,将“a”替换为“z”,将“B”替换为“Y”。我怎样才能为每个字符串制作它?
解决方案
请考虑这个解决方案:
来自 ASCII 表http://www.asciitable.com/
CHAR DECIMAL
"A" 65
"B" 66
...
"Y" 89
"Z" 90
如果我们想将 'B'(这是 'A' 之后的第二个字符)交换为 'Y'(这是从 'Z' 开始的倒数第二个字符),我们可能想要“从 'A' 和从'Z'中减去它,如'Z' - (x - 'A')
#include <string>
#include <iostream>
char invert_char(char x)
{
if (x >= 'a' && x <= 'z')
return char('a' -x + 'z');
if (x >= 'A' && x <= 'Z')
return char('A' -x + 'Z');
return x;
}
std::string invert_string(std::string str)
{
for (auto& c: str)
c = invert_char(c);
return str;
}
int main()
{
std::string test = "ABCDEF UVWXYZ";
std::cout << test << std::endl;
std::cout << invert_string(test) << std::endl;
return 0;
}
推荐阅读
- android - 如何解决flutter中的渲染溢出问题?
- reactjs - 如果输入只接受数字,则反应测试
- html - 如何在 SQL 查询中使用来自多个 Html 复选框的值?
- python - ValueError: I/O operation on closed file 为什么会这样?用 python book 自动化无聊的东西
- c - 为什么 FILE 结构总是用指针表示而不是自动变量?
- lua - 如何在 roblox 上获取模型的大小值
- javascript - 给我一些关于如何为 deno 安装liquid.js 库的提示
- php - 如何从数据库中获取数据作为 utf-8 CodeIgniter
- javascript - 按钮上的脉轮 UI colorScheme 道具
- c# - 我收到在 C# 中使用 bool 方法的错误消息