#include<stdio.h>
#define MAXLINE 80
#define M 26
int main() {
int i, offset;
char str[MAXLINE];
printf("enter a string:");
i = 0;
while ((str[i] = getchar()) != '\n') {
i++;
}
str[i] = '\0';
printf("Enter offset:");
scanf_s("%d", &offset);
if (offset >=M) {//当offset大于等于26时,移位效果相当于取其余数
offset = offset % M;
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i ]>= 'A' && str[i] <= 'Z') //分大小写
{
if ((str[i] - 'A' + offset) < M) //从0开始索引,A对应0,以此类推
{
str[i] += offset;
}
else//如果向后越界
{
str[i] = str[i] - (M - offset);
}
}
else if (str[i] >= 'a' && str[i] <= 'z') {
if ((str[i] - 'a' + offset) < M)
{
str[i] += offset;
}
else
{
str[i] = str[i] - (M - offset);
}
}
}
printf("After being encrypted:");
for (i = 0; str[i] != '\0'; i++) {
putchar(str[i]);
}
printf("\n");
return 0;
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i ]>= 'A' && str[i] <= 'Z') //分大小写
{
if ((str[i] - 'A' + offset) < M) //从0开始索引,A对应0,以此类推
{
str[i] += offset;
}
else//如果向后越界
{
str[i] = str[i] - (M - offset);
}
}
else if (str[i] >= 'a' && str[i] <= 'z') {
if ((str[i] - 'a' + offset) < M)
{
str[i] += offset;
}
else
{
str[i] = str[i] - (M - offset);
}
}
}
if (str[i ]>= 'A' && str[i] <= 'Z') { ... } else if (str[i] >= 'a' && str[i] <= 'z') { ... }检查字符大小写区分开
if ((str[i] - 'A' + offset) < M) { str[i] += offset; } else { str[i] = str[i] - (M - offset); }从0开始索引并加上偏移量,并检查是否小于26,防止后越界