求助:C# winform中如何去掉字符后面的空格?

yejunyan 2012-04-19 03:18:57
做了一个从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个空格去掉,只留一个空格?
...全文
417 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yejunyan 2012-04-19
  • 打赏
  • 举报
回复
对不起,搞错了,谢谢二楼和三楼!
yejunyan 2012-04-19
  • 打赏
  • 举报
回复
所有问题解决了,谢谢三楼的!
yejunyan 2012-04-19
  • 打赏
  • 举报
回复
谢谢三楼的,现在2012-01-01 10:00 和 0.5之间的7个空格去掉了。我在写字板中打开生成的txt文件,发现在0.5后面有一个空格和一个段落标记,请问怎么去掉?
hebeijg 2012-04-19
  • 打赏
  • 举报
回复
.ToString("yyyy/MM/dd")
liyifei123 2012-04-19
  • 打赏
  • 举报
回复
同意二楼。。。。
stonespace 2012-04-19
  • 打赏
  • 举报
回复
那不是空格而是制表符'\t',你自己程序把制表符写到二者之间,你只需要换成空格就行,

lz[j] += dr.ItemArray[i].ToString();
lz[j] += " ";
cancerser 2012-04-19
  • 打赏
  • 举报
回复
string str="2012-01-01 10:00 0.5";
str = System.Text.RegularExpressions.Regex.Replace(str, @"\s{2,}", " ");

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧