Как мне не превысить границы массива в шифре Vigenere?
После 4-го символа моя программа вылетает, возвращая эту ошибку:
Индекс находился вне границ массива. в System.String.get_Chars(индекс Int32) в Caesar_Cipher.Program.Main(String[] args)
Я действительно понятия не имею, как это исправить.
Вот код:
using System;
using System.Collections.Generic;
using System.Text;
namespace vigenere_Cipher {
class Program {
static void Main(string[] args) {
string text = string.Empty;
string key = string.Empty;
Console.Write("Enter the keyword: ");
key = Console.ReadLine();
for(int i = 0; i < key.Length; i++)
{
if(char.IsLetter(key[i]))
{
}
else
{
Console.WriteLine("a key must be alphabetical!");
}
}
Console.Write("Enter plaintext: ");
text = Console.ReadLine();
int counter = 0;
for(int j = 0; j <= text.Length; j++)
{
if(counter <= text.Length)
{
counter ++;
}
if(char.IsLetter(text[j]))
{
if(char.IsUpper(text[j]))
{
Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter] -65)% 26) + 65));
}
if(char.IsLower(text[j]))
{
Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter]-97)%26) + 97));
}
Console.Write("\n");
}
Console.ReadKey();
}
}
}
}
0 ответов
Измените свой второй цикл FOR на
for(int j = 0; j < text.Length; j++)