C語言程序:
#include?<stdio.h>#include?<string.h>
#define?MAX?100
int?isValidate(char?str[]);
int?isLetter(char?ch);
int?isLow(char?ch);
void?encrypt(char?source[],?char?dest[]);
void?main()
{
char?source[MAX];
char?dest[MAX];
printf("input?a?string?:?");
gets(source);
if(isValidate(source)?==?0)
{
printf("error\n");
return;
}
if(strlen(source)?>?20)
{
source[20]?=?'\0';
}
encrypt(source,?dest);
printf("encrypted?:?%s\n",?dest);
}
/*?判斷字符串str是否合法?*/
int?isValidate(char?str[])
{
int?i,?len;
len?=?strlen(str);
if(len?<=?0)
{
return?0;
}
for(i=0;?i<len;?i++)
{
if(isLetter(str[i])?==?0)
{
return?0;
}
}
return?1;
}
/*?判斷字符ch是否是字母?*/
int?isLetter(char?ch)
{
if((ch?>=?'a'?&&?ch?<=?'z')?||?(ch?>=?'A'?&&?ch?<=?'Z'))
{
return?1;
}
else
{
return?0;
}
}
/*?判斷字符ch是否是小寫字母?*/
int?isLow(char?ch)
{
if(ch?>=?'a'?&&?ch?<=?'z')
{
return?1;
}
else
{
return?0;
}
}
/*?加密字符串?*/
void?encrypt(char?source[],?char?dest[])
{
int?len?=?strlen(source);
for(int?i=0;?i<len;?i++)
{
if(isLow(source[i])?==?1)
{
dest[i]?=?(source[i]?-?'a'?+?4)?%?26?+?'a';
}
else
{
dest[i]?=?(source[i]?-?'A'?+?4)?%?26?+?'A';
}
}
dest[i]?=?'\0';
}
運行測試:
input?a?string?:?Chinaencrypted?:?Glmre