做了一个从sql server 中将数据导出到一个txt文件的小程序,代码中的datatime为datetime类型,根据需要datatime显示格式为yyyy-mm-dd hh:mm 生成文本文件后,datatime后面有7个空格(:00:000),怎么样才能将这7个空格去掉?
----------------------
namespace sql2txt
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            string dtxtyear;
            string dno;
            dtxtyear = txtyear.Text.Trim();
            dno = txtno.Text.Trim();                       if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string connstr = ConfigurationManager.ConnectionStrings["djrrdbConnString"].ConnectionString;
                
                SqlConnection sqlconn = new SqlConnection(connstr);
                sqlconn.Open();
                SqlDataAdapter sda = new SqlDataAdapter("Select convert(varchar(16),datatime,120),sdrain from rain where stationid=" + @dno + "  and year(datatime)=cast(" + @dtxtyear  + " as int) and (sdrain <>0) and (sdrain is not null) order by datatime", sqlconn);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                int RC = ds.Tables[0].Rows.Count;//得到数据的行数
                string[] lz = new string[RC];
                for (int j = 0; j < RC; j++)
                {
                    DataRow dr = ds.Tables[0].Rows[j];
                    for (int i = 0; i < dr.ItemArray.Length; i++)
                    {
                        lz[j] += dr.ItemArray[i].ToString();
                        lz[j] += "\t";
                    }
                    lz[j] += "\n";
                }
                string filename = saveFileDialog1.FileName;
                FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));//通过指定字符编码方式可以实现对汉字的支持,否则在用记事本打开查看会出现乱码
                sw.Flush();
                sw.BaseStream.Seek(0, SeekOrigin.Begin);
                string ts = "日期时间"  +  "\t" + "数据" ;                 
               
                sw.WriteLine(ts);
                for (int i = 0; i < RC; i++)
                {
                    
                    sw.WriteLine(lz[i]);                }
               
                sw.Flush();
                sw.Close();
                sqlconn.Close();
            }        }    }
}
程序运行后生成的文本文件为:
日期时间              数据
2012-01-01 10:00       0.5
2012-02-01 09:00       1.0
...........请问怎样将2012-01-01 10:00 和0.5之间的7个空格去掉,只留一个空格?

解决方案 »

  1.   

    string str="2012-01-01 10:00       0.5";
    str = System.Text.RegularExpressions.Regex.Replace(str, @"\s{2,}", " ");
      

  2.   

    那不是空格而是制表符'\t',你自己程序把制表符写到二者之间,你只需要换成空格就行,  lz[j] += dr.ItemArray[i].ToString();
       lz[j] += " ";
     
      

  3.   

    谢谢三楼的,现在2012-01-01 10:00 和 0.5之间的7个空格去掉了。我在写字板中打开生成的txt文件,发现在0.5后面有一个空格和一个段落标记,请问怎么去掉?