2

我正在尝试构建一个莫尔斯转换器,以下是我的 c# 代码的一部分,但是当我运行它时它告诉我索引超出范围,有人可以修复它吗?我是编程新手:)

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); 
4

4 回答 4

4

您看到此错误的原因是,如果在字符串中找不到给定的搜索词,IndexOf()它将返回一个值,因此当您尝试设置时,您会得到一个无效的索引。-1output[-1]

于 2015-04-03T03:43:17.223 回答
0

如果是我,我会保留每个字符的字典映射及其对应的莫尔斯字符串。这将使来回转换变得容易。

例如:

private static Dictionary<char, string> MorseMap = new Dictionary<char, string>
{
    {'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."},
    {'E', "."}, {'F', "..-."}, {'G', "--."}, {'H', "...."},
    {'I', ".."}, {'J', ".---"}, {'K', "-.-"}, {'L', ".-.."},
    {'M', "--"}, {'N', "-."}, {'O', "---"}, {'P', ".--."},
    {'Q', "--.-"}, {'R', ".-."}, {'S', "..."}, {'T', "-"},
    {'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"},
    {'Y', "-.--"}, {'Z', "--.."},{'1', ".----"}, {'2', "..---"}, 
    {'3', "...--"}, {'4', "....-"},{'5', "....."}, {'6', "-...."}, 
    {'7', "--..."}, {'8', "---.."},{'9', "----."}, {'0', "-----"},
    {'.', ".-.-.-"}, {',', "--..--"},{'?', "..--.."}, {'\'', ".----."},
    {'!', "-.-.--"}, {'/', "-..-."},{'(', "-.--."}, {')', "-.--.-"},
    {'&', ".-..."}, {':', "---..."},{';', "-.-.-."}, {'=', "-...-"},
    {'+', ".-.-."}, {'-', "-....-"},{'_', "..--.-"}, {'"', ".-..-."},
    {'$', "...-..-"}, {'@', ".--.-."}
};

现在,使用此映射中的键和值,很容易编码和解码为莫尔斯电码:

private static string ConvertToMorse(string input)
{
    var morse = new StringBuilder();

    foreach (var character in input)
    {
        var upperCaseChar = char.ToUpper(character);

        if (MorseMap.ContainsKey(upperCaseChar))
        {
            morse.Append(MorseMap[upperCaseChar]);
        }
        else
        {
            // If there's no mapping for this character, just add it
            morse.Append(character);
        }

        // Add a space between each morse string.
        morse.Append(' ');
    }

    return morse.ToString().Trim();
}

private static string ConvertToAlpha(string morse)
{
    var alpha = new StringBuilder();

    // Split words on double-spaces so we can add single spaces back where needed
    var morseCodeWords = morse.Split(new[] {"  "}, StringSplitOptions.None);

    foreach (var morseCodeWord in morseCodeWords)
    {
        var morseCodeStrings = morseCodeWord.Split(' ');

        foreach (var morseCodeString in morseCodeStrings)
        {
            if (MorseMap.ContainsValue(morseCodeString))
            {
                alpha.Append(MorseMap.First(item => item.Value == morseCodeString).Key);
            }
            else
            {
                // If there's no mapping for the string, just add it
                alpha.Append(morseCodeString);
            }
        }

        // Add a space between each word
        alpha.Append(' ');
    }

    return alpha.ToString();
}

使用示例:

private static void Main()
{
    var test = "This is my test string.";

    var morseVersion = ConvertToMorse(test);
    var alphaVersion = ConvertToAlpha(morseVersion);

    Console.WriteLine("Original string ... {0}", test);
    Console.WriteLine("Morse version ..... {0}", morseVersion);
    Console.WriteLine("Alpha version ..... {0}", alphaVersion);
}
于 2015-04-03T04:42:30.667 回答
0

如果在输入字符串中找不到指定的文本,IndexOf() 将返回 -1。只有在文本框中输入指定的字符时,您的代码才能正常工作。这就是为什么当您删除第二个循环并在文本框中输入所有 a 时您的代码可以正常工作的原因。

除此之外,为什么您需要使用 2 个循环。您在两个循环中都在做同样的事情。

于 2015-04-03T05:27:32.920 回答
0
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);

另外,如果您要为所有角色制作这些循环,我建议您这样做:

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);
于 2015-04-03T03:46:45.943 回答