Search code examples
c#convertersmorse-code

Index was outside the bounds of the array c#, morse converter


I was trying to build a Morse converter, the following is a part of my code of c#, but when I run it it tells me index out of the bounds, could anyone fix it? I'm new for programming:)

private void BTNconvert_Click(object sender, EventArgs e)
{           
    string input = TBinput.Text;
    string[] output=new string[input.Length];
    for (int index=0;index<input.Length;index++)
    {
        index=input.IndexOf('a',index);
        output[index]=".-";                                               
    }

    for (int index = 0; index < input.Length; index++)
    {
        index = input.IndexOf('b', index);
        output[index] = "-...";
    }

    LBcodes.Text = string.Join(" ",output); 

Solution

  • private void BTNconvert_Click(object sender, EventArgs e)
    {      
       int index;     
        string input = TBinput.Text;
        string[] output=new string[input.Length];
           index = -1;
            do{
                 index=input.IndexOf('a',index+1);
                 if(index==-1)break;
                 output[index]=".-";     
            }while(true);
            index = -1;
            do{
                 index=input.IndexOf('b',index+1);
                 if(index==-1)break;
                 output[index]="-...";     
            }while(true);
        }
    
        LBcodes.Text = string.Join(" ",output);
    

    also if you are going to make these loops for all of the characters I would recommand you to do this:

    private void BTNconvert_Click(object sender, EventArgs e)
    {  
    
       int index;
       char[] source1 = {'a','b','c',....,'z'} //replace ... with characters
       string[] source2 = {".-","-...",....}   //replace .... with Morse equivalents
        string input = TBinput.Text;
        string[] output=new string[input.Length];
           for(int i=0;i<26;i++){
           index = -1;
            do{
                 index=input.IndexOf(source1[i],index+1);
                 if(index==-1)break;
                 output[index]=source2[i];     
            }while(true);
            }
        }
    
        LBcodes.Text = string.Join(" ",output);