2014-01-07 19 views
1

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

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

回答

2

你可以试试这个

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

非常感谢! 尽管我将它更改为 ['a'+('z' - toCrypt [i])] ,因为这样更有意义(至少对我来说)。 – user2962533

1

在你的榜样,bamba,所有人物均成为第一个if语句:toCrypt[i] += symmetric_difference;

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

呃......谢谢你......(*刘海头上的墙*) – user2962533

0

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

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. :)