【问题标题】:Reversing alphabet value of individual characters in string by calculating the difference通过计算差异来反转字符串中单个字符的字母值
【发布时间】:2014-01-07 19:34:01
【问题描述】:

我正在尝试编写一个小函数,将小写字符翻转为字母表后半部分的对称对应字符 - 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];

我看了一遍,发现最接近的是 “反转字符串中单个字符的字母值”,但它描述了一种看起来很奇怪和多余的方式。

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

#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.
    }
}

【问题讨论】:

  • 我想你会发现symmetric_difference 是你正在寻找的值。计算很简单:toCrypt[i] = 121 - toCrypt[i]

标签: c++ c++11 reverse alphabet


【解决方案1】:

你可以试试这个

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

【讨论】:

  • 非常感谢!尽管我将其更改为 [ 'a' + ('z' - toCrypt[i]) ] 因为这样更有意义(至少对我而言)。
【解决方案2】:

在您的示例中,bamba,所有字符都进入第一个 if 语句:toCrypt[i] += symmetric_difference;。

toCrypt[i] += symmetric_difference;
-> toCrypt[i] = toCrypt[i] + 121 - toCrypt[i];
-> toCrypt[i] = 121 = 'y'

【讨论】:

    【解决方案3】:

    如果我没有打错,请尝试以下函数定义。

    void crypto( char s[] )
    {
        static const char alpha[] = "abcdefghijklmnopqrstuvwxyz"; 
        const char *last = alpha + sizeof( alpha ) - 1;
    
        while ( char &c = *s++ )
        {
          if ( const char *first = std::strchr( alpha, c ) ) c = *( last - ( first - alpha ) - 1 );
        }
    }   
    

    考虑到小写字母没有必要按顺序排列。例如,如果我没记错的话,它对 EBCDIC 无效。

    我想替换声明

    const char *last = alpha + sizeof( alpha ) - 1;
    

    为

    const char *last = alpha + sizeof( alpha ) - sizeof( '\0' );
    

    但最后一个与 C 不兼容。:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多