首页 > 解决方案 > 如何用相反的字母替换字符串中的每个字母?C++

问题描述

如何用相反的字母替换字符串中的每个字母?例如,将“a”替换为“z”,将“B”替换为“Y”。我怎样才能为每个字符串制作它?

标签: c++algorithm

解决方案


请考虑这个解决方案:

来自 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;
}


推荐阅读