字符串由用户输入。然后程序会根据输入对单词中的字符串进行移位。问题是,每当它试图移动 z 时,就会出现标点符号。如何克服这个问题?
printf("Enter text : ");
scanf("%s",&plaint);
printf("Enter shift amount : ");
scanf("%d",&shif);
for(int j=0; plaint[j] != '\0'; j++)
{
plaint[j]=plaint[j]+shif;
}
最佳答案
正如您在 ASCII code chart 中看到的那样在 Z
和 z
之后有标点符号。要从 z 跳转到使用模运算 (%
)。例如:
char plaint[101];
int shif;
printf("Enter text : ");
scanf("%100s",plaint);
printf("Enter shift amount : ");
scanf("%d",&shif);
for(int j=0; plaint[j] != '\0'; j++) {
if( plaint[j] >= 'A' && plaint[j] <= 'Z' )
plaint[j] = (plaint[j] -'A' + shif) % 26 + 'A';
if( plaint[j] >= 'a' && plaint[j] <= 'z' )
plaint[j] = (plaint[j] -'a' + shif) % 26 + 'a';
if( plaint[j] >= '0' && plaint[j] <= '9' )
plaint[j] = (plaint[j] -'0' + shif) % 10 + '0';
}
这只会移动字母和数字,并环绕 z 和 9。首先,我将字母移动到数值范围 0-25 内,将数字移动到 0-9 内,然后添加移位并使用模数,然后通过添加 'a'
(97)、'A'
(65) 或 '0'
移回其在 ASCII 图表中的原始位置(48)。
标点符号和其他字符不会更改。
关于c - 在 C 中移动单词时跳过标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36347615/