You can try this
for (int i = 0; i < size; i++)
{
toCrypt[i] = 'z' - toCrypt[i] + 'a';
}
Question
I'm trying to write a little function that will flip lowercase characters to their symmetric counterparts in the second half of the alphabet - 26 letters = 13/13.
a = z, b = y, c = x...
I've tried the following code but for some reason it works only for the first character.
Say I enter "bamba"; it begins by switching the 'b' to 'y' but then it gets stuck and replaces all the other character to 'y' as well and I get "yyyyy".
I tried playing around with the code a bit and discovered that if I remove dependency by the current character, I can safely increase all the letters by, say, 1 (a = b, b = c...)
symmetric_difference = 1; **commented out** //21 - toCrypt[i];
I looked all over and the closest thing I found was "Reversing alphabet value of individual characters in string" but it describes a way that seems weird and redundant.
Can anyone tell me what I did wrong please (assuming that I did)?
#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.
}
}
Solution
You can try this
for (int i = 0; i < size; i++)
{
toCrypt[i] = 'z' - toCrypt[i] + 'a';
}
OTHER TIPS
In your example, bamba
, all of the characters go into the first if statement: toCrypt[i] += symmetric_difference;
.
toCrypt[i] += symmetric_difference;
-> toCrypt[i] = toCrypt[i] + 121 - toCrypt[i];
-> toCrypt[i] = 121 = 'y'
Try the following function definition if I did not make a typo.
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 );
}
}
Take into account that it is not necessary that low case letters are ordered sequantially. For example if I am not mistaken it is not valid for EBCDIC.
I would like to substitute statement
const char *last = alpha + sizeof( alpha ) - 1;
for
const char *last = alpha + sizeof( alpha ) - sizeof( '\0' );
but the last is not compatible with C.:)