简体   繁体   English

在C ++中移动字符

[英]Shifting characters in C++

I tried to write a function to do simple shifting of characters (either to the left or right, depending on the shift parameter in the following function). 我试着编写一个函数来进行简单的字符移位(向左或向右移动,具体取决于以下函数中的移位参数)。 Capital letters remain to be capital letters. 大写字母仍然是大写字母。 Here is my approach: 这是我的方法:

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;
}

This function stops working properly when the input character is 's' and beyond. 当输入字符为's'时,此功能将停止正常工作。 Could anyone please point out what's the problem to my approach? 有人可以指出我的方法有什么问题吗?

Thanks in advance. 提前致谢。

's' + 13 will overflow a signed char . 's'+ 13将溢出一个签名的char Keep the result in an int and cast to char after adjusting the number and before returning. 保持结果为int并在调整数字后返回之前转换为char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM