c - 在 C 中移动单词时跳过标点符号

标签 c arrays char shift

字符串由用户输入。然后程序会根据输入对单词中的字符串进行移位。问题是,每当它试图移动 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 中看到的那样在 Zz 之后有标点符号。要从 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/

相关文章:

Javascript:如何根据数据对象数组检查混合用户输入?

java - 将数据存储在数组中好吗?

python - 过滤一行中有 n 个相等字符的字符串

c++ - 函数调用中char[]和char*的区别

c - 如何确定 write(2) 已将所有数据写入套接字/文件描述符?

c - 空指针数组: valgrind gives invalid write size of 8

c - 如果我分离一个已经加入的线程会发生什么?

php - 将数组值插入数据库时​​出错

C - 有没有办法处理中间有 NULL 字符的字符串

c - 我如何让它解码(Perl cbc-crypt 到 C cbc_crypt 转换)