数组IndexOutOfRange

时间:2013-07-18 16:16:35

标签: c# arrays indexoutofboundsexception

        string temp = textBox1.Text;
        char[] array1 = temp.ToCharArray();
        string temp2 = "" + array1[0];
        string temp3 = "" + array1[1];
        string temp4 = "" + array1[2];
        textBox2.Text = temp2;
        textBox3.Text = temp3;
        textBox4.Text = temp4;

当用户在textBox1中输入少于三个字母时,如何防止发生IndexOutOfRange错误?

4 个答案:

答案 0 :(得分:10)

  

如果用户只在textBox1中输入少于三个字母,我将如何阻止IndexOutOfRange错误?

只需使用temp.Length

进行检查
if (temp.Length > 0)
{
    ...
}

...或使用switch / case

此外,您根本不需要阵列。只需在每个字符上调用ToString,或使用Substring

string temp = textBox1.Text;
switch (temp.Length)
{
    case 0:
        textBox2.Text = "";
        textBox3.Text = "";
        textBox4.Text = "";
        break;
    case 1:
        // Via the indexer...
        textBox2.Text = temp[0].ToString();
        textBox3.Text = "";
        textBox4.Text = "";
        break;
    case 2:
        // Via Substring
        textBox2.Text = temp.Substring(0, 1);
        textBox3.Text = temp.Substring(1, 1);
        textBox4.Text = "";
        break;
    default:
        textBox2.Text = temp.Substring(0, 1);
        textBox3.Text = temp.Substring(1, 1);
        textBox4.Text = temp.Substring(2, 1);
        break;
}

另一个选择 - 甚至更整洁 - 是使用条件运算符:

string temp = textBox1.Text;
textBox2.Text = temp.Length < 1 ? "" : temp.Substring(0, 1);
textBox3.Text = temp.Length < 2 ? "" : temp.Substring(1, 1);
textBox4.Text = temp.Length < 3 ? "" : temp.Substring(2, 1);

答案 1 :(得分:0)

另一种方法是使用ElementAtOrDefault

    string[] temp = textBox1.Text.Select(c => c.ToString());
    string temp2 = "" + temp.ElementAtOrDefault(0);
    string temp3 = "" + temp.ElementAtOrDefault(1);
    string temp4 = "" + temp.ElementAtOrDefault(2);
    textBox2.Text = temp2;
    textBox3.Text = temp3;
    textBox3.Text = temp4;

答案 2 :(得分:0)

此类问题的一般解决方案是在访问其元素之前检查源值(数组,字符串或向量)的长度。例如:

string  temp = textBox1.Text;

if (temp.Length > 0)
    textBox2.Text = temp.Substring(0, 1);
if (temp.Length > 1)
    textBox3.Text = temp.Substring(1, 1);
if (temp.Length > 2)
    textBox4.Text = temp.Substring(2, 1);

答案 3 :(得分:0)

如果尺寸固定,即没有。字符是3或长度是3然后它必须像......

string temp = textBox1.Text; char[] array1 = temp.ToCharArray(); if(temp.length==3) { string temp2 = "" + array1[0]; string temp3 = "" + array1[1]; string temp4 = "" + array1[2]; textBox2.Text = temp2;
textBox3.Text = temp3; textBox3.Text = temp4; }
如果你的字符串长度是3 ....这将是有用的。