Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting characters in C++

Tags:

c++

character

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. Could anyone please point out what's the problem to my approach?

Thanks in advance.

like image 799
Roy Avatar asked Sep 14 '13 09:09

Roy


People also ask

How to shift characters in an array in C?

char str[] = "abcdef"; Save the first character, because it will be overwritten later: char tmp = str[0]; Then move the rest of the string one character forward.

How do you shift characters in a string?

So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer.

What is the ascii value of \n in C?

LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.


1 Answers

's' + 13 will overflow a signed char. Keep the result in an int and cast to char after adjusting the number and before returning.

like image 109
svk Avatar answered Oct 14 '22 18:10

svk