您的位置:首页 > 编程语言 > C#

c# 读取文本中的一行用逗号连接数据,并对其进行排序

2009-07-09 21:28 615 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace px3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{//用来打开文件的按钮
OpenFileDialog o = new OpenFileDialog();
o.Filter = "文本文件(*.txt)|*.txt";
if (o.ShowDialog()== DialogResult.Cancel) return;
this.textBox1.Text = o.FileName;//在文本框中写入打开的文件的文件名

}

private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
button1_Click(sender,e);//双击文本框也能打开文件
}

private void button3_Click(object sender, EventArgs e)
{
dataHandle();
}

private void dataHandle()
{
if (this.textBox1.Text == "")
return;
if (!System.IO.File.Exists(this.textBox1.Text))
{
MessageBox.Show(textBox1.Text + " 文件不存在");
return;
}
string result = "";
using(System.IO.StreamReader sr=new System.IO.StreamReader(textBox1.Text))
{
string s = sr.ReadLine();//读取文本中的一行数据
string []ss = s.Split(",".ToCharArray());//按逗号讲数据分割成一个数组
int[] si = new int[ss.Length];//定义一个新的数组的长度等于分割了的数组长度

for (int k = 0; k < si.Length; k++)//将字符数组转化为整数数组
{
si[k] = Convert.ToInt32(ss[k]);
}
result = px(si);
sr.Close();
}
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(textBox1.Text,true))
{
sw.WriteLine();
sw.WriteLine(result);
sw.Close();
}
}

private string px(int [] si)
{

//冒泡排序!
int zz;

for (int i = 0; i < si.Length-1; i++)
for (int j = 0; j <si.Length-i-1; j++)
{
if (si[j] > si[j + 1])
{
zz = si[j]; si[j] = si[j + 1]; si[j + 1] = zz;
}
}
string r = "";
for (int i = 0; i < si.Length; i++)
{
r = r + si[i].ToString() + ",";
}
r = r.Remove(r.Length - 1, 1);//将最好一个","去掉
return r;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐