读书人

C#读写文本 送分啊快进来抢分解决思路

发布时间: 2012-02-03 22:02:47 作者: rapoo

C#读写文本 送分啊!快进来抢分
这是我文本内容:
1234 43 54 23 554 231 4541
1232 423 514 354 31 441 1
1231 243 154 123 54 31 454
这些数据他们之间都是一个空格隔开的
我要将这些数据 不满足4位的在他前面不空格 让他满足4位

用C#代码怎么实现 请指教!


[解决办法]
先把文本取出来,用Regex.Split(...)来得到你的分开的数组String[],然后循环foreach来判断是否是4位数,
不足的补上就可以了。
[解决办法]

C# code
 
try
{
StreamReader sr = new StreamReader("test.txt");
StringBuilder sb = new StringBuilder();
while (!sr.EndOfStream)
{
string str = sr.ReadLine();
string[] temp = str.Split(' ');
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Length != 4)
temp[i] = temp[i].PadLeft(4, ' ');
}
str = string.Join(" ", temp);
sb.Append(str + "\n");
}
sr.Close();
string[] result = sb.ToString().Split("\n".ToCharArray());
StreamWriter sw = new StreamWriter("test.txt", false);
foreach (string s in result)
sw.WriteLine(s);
sw.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

[解决办法]
C# code
StreamReader sr = new StreamReader(@"D:\1.txt");using (StreamWriter sw = new StreamWriter(@"D:\2.txt", true)){    while (sr.Peek() != -1)    {        string[] temp = sr.ReadLine().Split(' ');        for (int i = 0; i < temp.Length; i++)            temp[i] = temp[i].PadLeft(4, ' ');        string s = string.Join(" ", temp);        sw.WriteLine(s);    }}sr.Close(); 

读书人网 >C#

热点推荐