c - 如何将字符串的每个字母转换为另一个字母?在 C 中
问题描述
这是我的第一篇文章,如果格式不合适,请告诉我。谢谢。我目前正在尝试设计一种算法来做这样的事情:
它要求不同的字母组成一个 n 位数字的字符串,然后它要求一个密钥字母“密码密钥”,然后它转换字符串的每个字母加上密钥字母,例如:
How many characters? 3
Next character (1/3)? h
Next character (2/3)? a
Next character (3/3)? l
-> [ h a l ]
Caesar cypher key? b
Encrypting...
-> [ i b m ]
在这里,我留下另一个代码应该做什么的例子:
How many characters? 3
Next character (1/3)? z
Next character (2/3)? h
Next character (3/3)? h
-> [ z h h ]
Caesar cypher key? a
Encrypting...
-> [ z h h ]
在此示例中,当 a=0 时,字母将是相同的
如您所见,它要求输入一定数量的字符,即字符串的大小,然后您可以输入数字,然后打印数字,然后要求输入密钥字母,“加密”字符串,然后然后它显示相同的字符串,但将键字母的值添加到字符串的每个字母中。
显然,必须使用 ASCII 表才能做到这一点。
我不太擅长使用字符串和函数,所以我可能会导致一些错误。
在这里,我将带有注释(//...)的代码留给您查看:
#include <stdio.h>
#include <string.h>
#define SIZE 20
//argument with no return value function to change the value of str1 with the 'cypher key'.
void moveLetters (char str1[], char cypher_key) {
int i;
int len;
len = strlen(str1);
//loop to convert every character of the string with the cypher key value
for (i = 0; i < len; i++) {
str1[i] = (str1[i] + cypher_key - 97 * 2) % 26 + 97;
}
}
int main () {
int n_characters;
char str1[SIZE];
char cypher_key;
int i;
int t = 0;
//asks for the amount of values of the string which can't be less than 0.
do {
printf ("How many characters? ");
scanf ("%d", &n_characters);
} while (n_characters <= 0);
//asks for every character depending on the amount.
for (i = n_characters; i > 0; i--) {
printf ("Next character (%d/%d)? ", t + 1, n_characters);
scanf ("%s", &str1[t]);
t++;
}
printf ("-> [%s]\n", str1);
printf ("Caesar cypher key? ");
scanf ("%s", &cypher_key);
//here I have my doubts because i don't really know if this is a correct way to send a value to a
//function and return it to the main
moveLetters (str1, cypher_key);
printf ("Encrypting...\n");
printf ("-> [%s]", str1);
return 0;
}
发生的事情是由于某种原因它在最后一个 printf 中什么也没打印,所以我不明白 void 函数或其他地方发生了什么。
解决方案
推荐阅读
- node.js - 使用 Node.js (+ express) 服务器在 OpenWrt 中执行 shell 命令
- reactjs - 如何将道具传递给动态路线?
- html - 我想让滚动条与滚动条拇指一起在 div 中始终可见
- javascript - 在 Javascript 中调用 Flask-Wtform 提交按钮
- php - 根据单击的复选框进行过滤
- java - 我如何比较java中的两个JSONArray?
- javascript - 外部点击在angularjs中不起作用
- neighbours - 如何获取地图中特定点周围的一组最近点?
- vb.net - SQL UPDATE 语句 - 使用 WHERE 的列名无效
- reactjs - 如何防止在 ReactJS 的 URL 中添加字符串?