日期:2014-05-17  浏览次数:20784 次

C#最简答的一个问题
string a = "中国,欢迎#你";
  char[] c ={ ',', '#' };
  string [] b=new string[100];  
  b = a.Split(c);
  for (int i = 0; i<a.Length; i++) 
  { 
   
  Console.Write("item{0}:{1}",i,b[i]);

  }
   
  Console.ReadLine();



上面语句执行,提示索引超出了数组界限,请各位大哥帮忙指点。

------解决方案--------------------
你看看b有几个元素啊,肯定a.Length大于b的长度
------解决方案--------------------
for (int i = 0; i<a.Length; i++)
====================================
for (int i = 0; i<b.Length; i++)
------解决方案--------------------
for (int i = 0; i < a.Length; i++)
=>
 for (int i = 0; i < b.Length; i++)
------解决方案--------------------
修改后的运行结果:

item0:中国item1:欢迎item2:你

------解决方案--------------------
string a = "中国,欢迎#你";
char[] c ={ ',', '#' };
string [] b=new string[100];
b = a.Split(c);
for (int i = 0; i<a.Length; i++) a中含有,# 比b多2个长度 必然越界
{

Console.Write("item{0}:{1}",i,b[i]);

}

Console.ReadLine();
------解决方案--------------------
b里面有三个字符串,“中国”,“欢迎”,“你”,长度3,而a的长度是7,肯定越界,你笔误把b.length写成a.length了吧
------解决方案--------------------
string a = "中国,欢迎#你";
char[] c ={ ',', '#' };
string [] b=new string[100];
b = a.Split(c);
for (int i = 0; i<b.Length; i++)
{

Console.Write("item{0}:{1}",i,b[i]);

}

Console.ReadLine();