我在C#中有这个代码,但是在块内移位的代码会覆盖用于移位d
个字母的代码。我怎样才能解决这个问题,以免他们不再相互覆盖?
这是代码:
private void Crypt(int n, int m, int d)
{
// make a block from the string
string invoerstring = invoer.Text;
uitvoer.Text = invoerstring;
// shift d letters
char[] buffer = invoerstring.ToCharArray();
for (int i = 0; i < buffer.Length; i++)
{
// Letter.
char letter = buffer[i];
// Add shift to all.
letter = (char)(letter + d);
// Subtract 26 on overflow.
// Add 26 on underflow.
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
// Store.
buffer[i] = letter;
}
uitvoer.Text+=buffer;
//shift characters inside a block
var shift = String.Concat(invoerstring.Skip(m).Concat(invoerstring.Take(m)));
uitvoer.Text = shift;
}
private void button1_Click(object sender, EventArgs e)
{
Crypt(8,2,1);
}
答案 0 :(得分:0)
一些提示:
Uitvoer
。尽力强制防止这种情况发生。从逻辑中分离UI代码(修改UI组件)(加密某些东西)。它只考虑这个提示你应该成功,因为现在你试图早点回复你的结果。invoerstring
,但invoerstring
没有被移动字母的代码以任何方式修改。您应该使用上一个操作的结果:buffer
。n
从未使用过?试试这个:
private string Crypt(string input, int m, int d)
{
string result = "";
foreach(char ch in input)
{
// Add shift to all.
char letter = (char)(ch + d);
// Subtract 26 on overflow.
// Add 26 on underflow.
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
// Store.
result += letter;
}
//shift characters inside a block
result = result.Substring(m) + result.Substring(0, m);
return result;
}
private void button1_Click(object sender, EventArgs e)
{
uitvoer.Text = Crypt(invoer.Text, 2, 1);
}
如果您希望显示块移位和charachter移位:在最后一行添加+
:
result += result.Substring(m) + result.Substring(0, m);
答案 1 :(得分:-1)
您正在使用我认为是问题的uitvoer.Text+=buffer;
。 char数组的类型在此处被指定为文本'System.Char []'。
下面修改的代码用下一个第d个字符替换每个字符(所以'a'被'b'替换)然后将字符向左旋转m个字符。
e.g。输入'abcde'给出o / p'debbc',其中m = 2且d = 1 [abcde - &gt; bcdef(替换为下一个字符) - &gt; defbc(向左移动2)]
private static void Crypt(int n, int m, int d)
{
// make a block from the string
string invoerstring = invoer.Text;
string uitv = "";
// shift d letters
char[] buffer = invoerstring.ToCharArray();
for (int i = 0; i < buffer.Length; i++)
{
// Letter.
char letter = buffer[i];
// Add shift to all.
letter = (char)(letter + d);
// Subtract 26 on overflow.
// Add 26 on underflow.
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
// Store.
buffer[i] = letter;
uitv += letter;
}
//shift characters inside a block
var shift = String.Concat(uitv.Skip(m).Concat(uitv.Take(m)));
uitv = shift;
uitvoer.Text = uitv;
}