当前位置:编程学习 > C#/ASP.NET >>

给出一段程序,帮我改改如何提高效率,谢谢!!

问题:
*.txt 里面的内容如下: 
1.24124  2.424124  3.1414  -123.42 ... 
2.24124  -2.42412  2.31314  231.42 ... 
-3.4154  1.422124  2.31314  31.422 ... 
... 
... 
... 
... 
如何用程序实现快速查找负数并替换为零,麻烦给个详细一点的程序!替换后的仍然保存在*.txt中

以下程序是某个兄弟提供,本人做些修改后的,看能不能修改提高效率!(因为*.txt数据非常大,有几百M)

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "转换";
            string dir = @"D:\";
            openFileDialog1.InitialDirectory = dir;
            string filter = "所有文件(*.*)|*.*";
            openFileDialog1.Filter = filter;
            // openFileDialog1.ShowDialog();
            openFileDialog1.Multiselect = false;
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            { MessageBox.Show("读取文件失败!"); }
            else
            {
                string filepath = @openFileDialog1.FileName; //文件路径
                String result = String.Empty;
                using (StreamReader reader = new StreamReader(filepath))//读取文件内容
                {
                    String line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        result += ReplaceMinusNumber(line);
                        result += System.Environment.NewLine;
                    }
                    reader.Close();
                   
                }

                using (StreamWriter writer = new StreamWriter(filepath))//将数据写入文件
                {
                    writer.Write(result);
                    writer.Close();
                }
            }
        }
        

        private String ReplaceMinusNumber(string line)
        {
            String result = String.Empty;
            String[] numbers = line.Split(' ');//拆分空格
            for (int i = 0; i < numbers.Length; i++)
            {
                if (numbers[i].StartsWith
                {
                    result += "0.23";
                    continue;
                }
                result += numbers[i] + " ";
            } 

            return result;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
      
    } --------------------编程问答-------------------- 帮LZ顶,已经很不错了。 --------------------编程问答-------------------- 如果要考效率的话

文件不一次一次加入,一次加入一段

不要用split,这个方法估计里面有很多开销的,
建议一次比较一个字符,如果是“-”号就是开始循环装入容器,遇到空格或者回车就停止装入,然后寻找下个“-”;

还有建议用stringbuilder代替string

--------------------编程问答-------------------- 不要用Split,找到减号以后找它后面第一个空格,把这部分用0代替就成了
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,