编写的程序有对字符串加密和解密的功能
对字符串的加密即是对每个字符往后偏移K值(例如K为2):
A->C C->E a->c c->e
Z->B z->b
而对字符串的解密即是对每个字符往前偏移K值(例如K为2):
A->Y Y->W a->y y->w
Z->X z->x
接下来我们需要考虑程序的具体实现:
首先我们需要把输入的字符串保存下来;
然后遍历字符串中每个字符,在遍历的工程中我们需要对每个字符的ASCII加K(或减K)并保存
遍历时我们需要注意两点 :
一是过滤掉空格 我们只需要在每次遍历的一开始加上if判断,判断字符是否为空格如果是空格我们不执行任何代码,不是空格执行下面代码
二是 要考虑到如果 字符的ascill加上K值超出了26个字母的ASCII码的范围,我们则需要计算出超出的值并在A或a的ASCII值上加上对应的超出值;如果是字符的ascill减去K值超出了26个字母的ASCII码的范围,我们则需要计算出超出的值并在Z或z的ASCII值上减去对应的超出值
最后我们需要强制转换把字符的int型转换成char,这样才能显示出字符。
首先我们要先画一个图形界面
如图(简单点就行):
这里的K值是偏移量 加密的话就是往后偏移K个位置 解密就是往前偏移K个位置
然后我们双击加密按钮加入Form1.cs编写代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 凯撒密码
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// while (true)//直接将程序放入死循环,方便做测试
output.Clear();
jiami();
}
public void jiami()
{
string inPut = insert.Text;//定义一个字符串,接收用户的输入
int key = Convert.ToInt32(Kcode.Text) % 26;
char res;
foreach (char c in inPut)//遍历字符串
{
if (c != 32)
{
if (!char.IsUpper(c))
{
if (c + key > 122)
{
int a1 = c + key - 122;
res = Convert.ToChar(96 + a1);
}
else
{
res = Convert.ToChar(c + key);
}
output.AppendText(res.ToString());
}
if (char.IsUpper(c))
{
if (c + key > 90)
{
int a1 = c + key - 90;
res = Convert.ToChar(64 + a1);
}
else
{
res = Convert.ToChar(c + key);
}
output.AppendText(res.ToString());
}
}
}
}
public void jiemi1()
{
string inPut = insert.Text;//定义一个字符串,接收用户的输入
int key = Convert.ToInt32(Kcode.Text) % 26;
char res;
foreach (char c in inPut)//遍历字符串
{
if (c != 32)
{
if (!char.IsUpper(c))
{
if (c - key < 97)
{
int a1 = 97-(c - key );
res = Convert.ToChar(123- a1);
}
else
{
res = Convert.ToChar(c - key);
}
output.AppendText(res.ToString());
}
if (char.IsUpper(c))
{
if (c - key < 65)
{
int a1 =65-(c - key);
res = Convert.ToChar(91- a1);
}
else
{
res = Convert.ToChar(c -key);
}
output.AppendText(res.ToString());
}
}
}
}
private void jiemi_Click(object sender, EventArgs e)
{
output.Clear();
jiemi1();
}
}
}
这样一个简单的图形界面凯撒密码就做好了 如有不足 还请大神指教