c# 中 数组长度为0时的问题。求解!谢谢~

string[] str1 = { };
Console.WriteLine(str1.Length);
string s = "";
int i = 0;
while (i < str1.Length - 1)
{
s = s + str1[i];
i++;
}
s = s + str1[str1.Length-1];
为什么在执行到while (i < str1.Length - 1)时,程序不会出现问题,而在执行最后一行代码 s = s + str1[str1.Length-1];出现问题。

string[] str1 = { }; //没有赋值的数组
Console.WriteLine(str1.Length); //输出0
string s = "";
int i = 0;
while (i < str1.Length - 1) //等同于 while (i < - 1)所以不会进入while语句
{
s = s + str1[i];
i++;
}
s = s + str1[str1.Length-1];//str1[-1] (1).数组最小索引应为0,(2).由于你声明的数组是为空的,所以就算你改成str1[0],这样也是错的。
解决方案:
声明有值的数组:string[] str1 = {"test001","test002"}; ,并将while判断语句改为:while (i <= str1.Length - 1)
s变量得到的值应为:test001test002test002
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-01-07
因为str1.Length - 1 = -1,
while 循环根本没转,所以没问题。
但你希望求str1[str1.Length-1]值得时候str1[-1]不存在。
第2个回答  2013-01-07
因为while (i < str1.Length - 1)这句不成立,则s=s+str1[i]这句不会执行,所以不出错。而s = s + str1[str1.Length-1];这句是没加判断就直接执行的,就会错了
第3个回答  2013-01-07
因为i=0 你的判断i<str1.Length-1 这个判断要成立的话 也就是说str1.Lenght-1=-1才可以 所以这段程序有问题 即使当str1.Length-1=0 他也不会退出 修改为<=即可
相似回答