通过计算差值来反转字符串中单个字符的字母值
Reversing alphabet value of individual characters in string by calculating the difference
我正在尝试编写一个小函数,该函数将在字母表的后半部分将小写字符翻转为对称对应字符 - 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.
}
}
你可以
试试这个
for (int i = 0; i < size; i++)
{
toCrypt[i] = 'z' - toCrypt[i] + 'a';
}
在您的示例中,bamba
,所有字符都进入第一个 if 语句:toCrypt[i] += symmetric_difference;
。
toCrypt[i] += symmetric_difference;
-> toCrypt[i] = toCrypt[i] + 121 - toCrypt[i];
-> toCrypt[i] = 121 = 'y'
如果我没有打错字,请尝试以下函数定义。
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( ' ' );
但最后一个与 C.:) 不兼容
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 为什么char不是单个字符
- 使用单个变量对字符输入进行计数
- 将字符向量转换为单个字符串
- C++ 字符串单个字符
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 将单个字符转换为 std::string 前缀 \x01
- 将单个字符串/字符输入串行监视器
- 尝试一次将单个字符读取到大小不确定的数组中
- C++ 如何将字符串拆分为单个字符
- 如何在C++中将单个字符哈希为相对较小的素数?
- 如何将像'A'这样的单个字符替换为类似"10"?
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- std::bad_alloc 将文本文件中的单个字符存储到矢量C++中时
- 查找单个字符串中重复次数最多和次数第二多的字符
- 如何从用户那里获取单个字符,直到他输入"."或输入
- 字符串中单个字符作为数组的数据类型是什么
- 字符串中的重音,如何在单个字符中存储重音字符
- 从字符串中提取单个字符并将其转换为 int