数组索引超出范围

本文关键字:范围 索引 数组 | 更新日期: 2023-09-27 18:23:52

        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 中输入少于三个字母时发生索引超出范围错误?

数组索引超出范围

如果用户在textBox1中仅输入少于三个字母,我将如何防止索引超出范围错误?

只需使用 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);

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

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

另一种方法是使用 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;

如果大小是固定的,即字符的否是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,这将工作。