c++ - 通过计算差异来反转字符串中各个字符的字母值

标签 c++ c++11 reverse alphabet

我正在尝试编写一个小函数,将小写字符翻转为字母表后半部分的对称对应字符 - 26 个字母 = 13/13。

a = z, b = y, c = x...

我试过下面的代码,但出于某种原因它只对第一个字符有效。

假设我输入“bamba”;它首先将“b”切换为“y”,但随后卡住并将所有其他字符也替换为“y”,我得到“yyyyy”。

我尝试了一些代码,发现如果我删除当前字符的依赖性,我可以安全地增加所有字母,比如说,1 (a = b, b = c...)

symmetric_difference = 1; **commented out** //21 - toCrypt[i];

我四处寻找,我找到的最接近的东西是 “Rolling alphabet value of individual characters in string”但是它描述了一种看起来奇怪和多余的方式。

谁能告诉我我做错了什么(假设我做错了)?

#include <iostream>
using namespace std;

void crypto(char[]);

int  main()
{
    char toCrypt[80];

    cout << "enter a string:\n";
    cin >> toCrypt;

    crypto(toCrypt);

    cout << "after crypto:\n";
    cout << toCrypt;
}

void crypto(char toCrypt[]) // "Folding" encryption.
{
    int size = strlen(toCrypt);
    int symmetric_difference;

    for (int i = 0; i < size; i++)
    {
        symmetric_difference = 121 - toCrypt[i];    // Calculate the difference the letter has from it's symmetric counterpart.

        if (toCrypt[i] >= 97 && toCrypt[i] <= 110)  // If the letter is in the lower half on the alphabet,
            toCrypt[i] += symmetric_difference; // Increase it by the difference.
        else
        if (toCrypt[i] >= 111 && toCrypt[i] <= 122) // If it's in the upper half,
            toCrypt[i] -= symmetric_difference; // decrease it by the difference.
    }
}

最佳答案

你可以试试这个

for (int i = 0; i < size; i++)
{
   toCrypt[i] = 'z' - toCrypt[i] + 'a';
}

关于c++ - 通过计算差异来反转字符串中各个字符的字母值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20980187/

相关文章:

C++ 创建一个静态类来存储指针

c++ - 启用 Direct3D 特定功能(透明 AA)

c++ - 将模板化类转换为更通用的特化

c++ - 将 multi_key 映射转换为连接多个键的 "normal"映射

c++ - 如果 'foo' 是引用变量, [&foo]{ ... } 捕获和 [foo]{ ... } 捕获之间有区别吗?

c++ - 通过 lambda 捕获列表中的常量引用传递

具有两个参数的模板的 C++ 友元函数

c - 无法打印以相反顺序输入到数组中的数字

javascript - 在 mousemove Javascript 事件中反转动画?

PHP 多维 array_reverse 值