如何旋转char一定数量的字母?

时间:2015-08-20 09:18:41

标签: rotation char

我不确定如何做到这一点,但是如何从用户输入的abcs中将一个字符从一个字符移动到另一个字符?我如何将它保持在一个圆圈中? (如果char是z,那么编译器会知道它应该转到a并重新开始吗?)

提前致谢

int encode( int ch, int shift );

  printf( Move the characters to the right or left? "%c/n" );

if ( right ){

    printf ( Rotate right by how much? "%i/n");
    scanf ( "%i" );
        if ( %i >= 1 ){
            %i++;
        } else if ( %i <= 1 )
            %i--;
    }


} else if ( left ) {
    printf ( Rotate left by how much? "%i/n" );
    scanf ( "%i" );
        if ( %i >= 1 ){
            %i++;
        } else if ( %i <= 1 )
            %i--;
}

1 个答案:

答案 0 :(得分:0)

我假设你的代码很少有编程经验,所以我会详细解释这个简单问题是如何解决的。

我用C语言编写了代码:

char encode(char letter, int shift){

    char direction[6];

    printf( "Move the characters to the left or right (left/right)? ");
    scanf("%s", direction);

    if(strcmp(direction, "left") == 0){
        if((letter - shift) < 'A')
            return (letter - shift) + 26;
        else
            return letter - shift;

    } else if(strcmp(direction, "right") == 0) {
        if((letter + shift) > 'Z')
            return (letter + shift) - 26;
        else
            return letter + shift;

    } else 
        printf("UNKNOWN COMMAND!\n");

    return letter;
}

检查它所在的行:

if((letter - shift) < 'A')

这意味着,如果您将转移到“A”以下,则需要添加26 (字母表中的字母数字)才能找到正确的字母。

同样适用于此,但您检查是否将转移到“Z”以上扣除26 以获得正确的字母:

if((letter + shift) > 'Z')

否则,如果您处于'A'和'Z'的边界,只需添加/减去当前字母的移位。

我向你展示了一个关于大写字母的例子,但同样的事情适用于较低的字母。