日期:2014-05-19  浏览次数:20873 次

ArrayList 奇怪的地方
public   static   void   MC(string   msg)
    {
      int   msgCount   =   msg.Length   /   10   +   (   msg.Length   %   10   ==   0   ?   0   :   1);
     
      string[]   msgList   =   new   string   [msgCount];

      for(int   i   =   1;   i   <=   msgCount;   i   ++)
      {
        string   Message   =   msg;
        if   (i   ==   msgCount)
        {
              Message   =   msg;
        }
        else
        {
              Message   =   msg.Substring(0,10);
              msg   =   msg.Substring(10,msg.Length   -   10);
        }

            List.Add(Message);    
      }
    }

上面的代码的意思是.要将一段文字按照10个字的长度分割.然后放到一个ArrayList的对象里面去.
但是,执行完毕后,发现   List   里面的的对象并没有保存每一段,而只是保存了最后的一部门.

例如:abcdefghijklmnopqrst   这个字符串,按照     5个字符长度分割,正确的结果应该是

abcde

fghij

klmno

pqrst

但是执行出来看到是却是

pqrst

pqrst

pqrst

pqrst

pqrst

这是什么情况啊?


------解决方案--------------------
大哥,我帮你5个字符也调了,10个字符也调了。没问题啊,你其他地方错了吧!
------解决方案--------------------
static ArrayList List = new ArrayList();
static void Main(string[] args)
{
string a = "abcdefghijklmnopqrst ";
MC(a);
for (int i = 0; i < List.Count; i++)
{
Console.WriteLine(List[i].ToString());
}
Console.Read();
}

public static void MC(string msg)
{
int msgCount = msg.Length / 5 + (msg.Length % 5 == 0 ? 0 : 1);

string[] msgList = new string[msgCount];

for (int i = 1; i <= msgCount; i++)
{
string Message = msg;
if (i == msgCount)
{
Message = msg;
}
else
{
Message = msg.Substring(0, 5);
msg = msg.Substring(5, msg.Length - 5);
}

List.Add(Message);
}
}