-1

I'm trying to create a method that subs letters from a shuffled alphabet into the letters of an input but I keep getting IndexOutOfRange and don't know why.

In the debugger it says letterIndex equals -1 but I don't know how.

        private string SubCypher(string input, string charsToSub)
    {

        char[] charsToSubArr = charsToSub.ToCharArray();
        char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
        char[] inputChars = input.ToCharArray();

        for(int index = 0; index < inputChars.Length; index++)
        {
            char toBeSubbed = inputChars[index];

            int letterIndex = Array.IndexOf(alphabet, toBeSubbed);

          inputChars[index] = charsToSubArr[letterIndex];
        }



        return new string(inputChars);
    }

    private void transformButton_Click(object sender, EventArgs e)
    {
        string input = inputTextBox.Text;

        switchCaseTextBox.Text = SwitchCase(input);

        reverseTextBox.Text = Reverse(input);

        pigLatinTextBox.Text = PigLatin(input);

        shiftTextBox.Text = ShiftCypher(input, 3);

        subTextBox.Text = SubCypher(input, "NBAJYFOWLZMPXIKUVCDEGRQSTH");

    }

2 Answers2

1

when you call String.IndexOf(Char) if the char is not found it return -1. the same happens to Array.IndexOf(Array, ArrayObject)

whats happening is that your not finding the specified letter.also you should remove the char[] for alphabet and keep it as a String, and call String.IndexOf(Char), this will make the code run faster.

here a good fix for the problem:

for(int index = 0; index < inputChars.Length; index++)
{
    char toBeSubbed = inputChars[index];
    int letterIndex = Array.IndexOf(alphabet, toBeSubbed);
    if(letterIndex>0)
        inputChars[index] = charsToSubArr[letterIndex];
}
0

letterIndex = -1 means alphabet array doesn't contain char toBeSubbed. So your input parameter may contain lowercase alphabet chars or numbers/symbols.

Try to call ToUpper() on input string before passing it to SubCypher method:

subTextBox.Text = SubCypher(input.ToUpper(), "NBAJYFOWLZMPXIKUVCDEGRQSTH");
opewix
  • 4,993
  • 1
  • 20
  • 42