字符变换(好像是二级的题)? Anthony

//isalpha和isupper函数是标准库函数,其的简要功能如下:
int islower(int c)
{
    return 'a' <= c && c <= 'z';
}
int isupper(int c)
{
    return 'A' <= c && c <= 'Z';
}
int isalpha(int c)
{
    return islower(c) || isupper(c);
}

//testXXXX函数是测试用例.
////////////////////////////////////////////////////////////////
#include <assert.h>
#include <ctype.h>
#include <stdio.h>

char Postpone(char orig, int distance)
{
    //不处理非字母
    if (isalpha(orig) == 0)
    {
        return orig;
    }

    int d = distance % 26;
    char top = (isupper(orig) ? 'Z' : 'z') - d;

    //隐含orig < base + 4, 因为isalpha(orig)
    if (orig > top)
    {
        d -= 26;
    }

#ifndef NDEBUG
    printf("if '%c'[%3d] > '%c'[%3d] then put off %3d get %c[%3d]n", orig, orig, top, top, d, orig + d, orig + d);
#endif
    return orig + d;
}
void testPostponeNoneAlpha()
{
    assert(Postpone(' ', 4) == ' ');
    assert(Postpone('_', 4) == '_');
    assert(Postpone('~', 4) == '~');
}

void testPostpone4Letter()
{
    assert(Postpone('A', 4) == 'E');
    assert(Postpone('a', 4) == 'e');

    assert(Postpone('V', 4) == 'Z');
    assert(Postpone('v', 4) == 'z');

    assert(Postpone('W', 4) == 'A');
    assert(Postpone('w', 4) == 'a');

    assert(Postpone('Z', 4) == 'D');
    assert(Postpone('z', 4) == 'd');
}

void testPostpone0Letter()
{
    assert(Postpone('V', 0) == 'V');
    assert(Postpone('v', 0) == 'v');

    assert(Postpone('W', 0) == 'W');
    assert(Postpone('w', 0) == 'w');

    assert(Postpone('Z', 0) == 'Z');
    assert(Postpone('z', 0) == 'z');
}

int main()
{
    testPostponeNoneAlpha()
    testPostpone4Letter();
    testPostpone0Letter();
    return 0;
}

原文地址:https://www.cnblogs.com/ahuangliang/p/5309284.html