gpt4 book ai didi

c# - 拆分字符串时索引越界异常

转载 作者:行者123 更新时间:2023-12-02 22:12:07 25 4
gpt4 key购买 nike

我写了这个分割字符串的代码

 protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
string oldstr = DropDownList2.SelectedItem.Value;

string[] exp = System.Text.RegularExpressions.Regex.Split(oldstr, "-");
int int1 = Convert.ToInt32(exp[0]);
int int2 = Convert.ToInt32(exp[1]);
}

它给了我异常(exception)

"Index was outside the bounds of the array."

在行 int int2 = Convert.ToInt32(exp[1]);

        <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" 
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1-2">1-2 years</asp:ListItem>
<asp:ListItem Value="3-4 ">3-4 years</asp:ListItem>
<asp:ListItem Value="5-7">5-7 years</asp:ListItem>
</asp:DropDownList>

最佳答案

像这样更新你的标记

<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" 
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Value="0-0"></asp:ListItem> // add 0 and 0
<asp:ListItem Value="1-2">1-2 years</asp:ListItem>
<asp:ListItem Value="3-4">3-4 years</asp:ListItem>//remove space after 4
<asp:ListItem Value="5-7">5-7 years</asp:ListItem>
</asp:DropDownList>

而不是像下面那样使用 TryParse 转换并检查拆分数组的长度

//string[] exp = System.Text.RegularExpressions.Regex.Split(oldstr, "-");
//use string split rathre than using regular expression because character split is
// faster than regular expression split
string[] exp = oldstr.Split('-');
if(exp.Length>0)
{
int int1;
if(int.TryParse(exp[0], out num1))
{ // further code }
int int2;
if(int.TryParse(exp[1], out num1))
{ // further code }
}

关于c# - 拆分字符串时索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com