【发布时间】:2013-09-14 09:39:00
【问题描述】:
我尝试编写一个函数来进行简单的字符移动(向左或向右,取决于以下函数中的 shift 参数)。大写字母仍然是大写字母。这是我的方法:
char encodeCaesarCipherChar(char ch, int shift)
{
char result;
if (!isalpha(ch)) return ch;
result = ch + shift;
if (islower(ch) && result < 'a') {
result += int('z') - 1;
result -= int('a');
} else if (islower(ch) && result > 'z') {
result -= int('z');
result += int('a') - 1;
} else if (isupper(ch) && result < 'A') {
result += int('Z') - 1;
result -= int('A');
} else if (isupper(ch) && result > 'Z') {
result -= int('Z');
result += int('A') - 1;
}
return result;
}
当输入字符为 's' 及以上时,此功能将停止正常工作。谁能指出我的方法有什么问题?
提前致谢。
【问题讨论】:
-
你为测试提供的
shift的值是多少? -
int('z') - 1不需要从字符文字到整数类型的转换,因为char是整数类型(不是int,而是整数)。 -
至少对于某些价值观来说,它就像魅力一样。可以提供调用代码吗?
-
Re timrau,我使用了值 13 作为 shift 参数。
-
使用
unsigned char代替字符