这是我文本内容:
1234 43 54 23 554 231 4541
1232 423 514 354 31 441 1
1231 243 154 123 54 31 454
这些数据他们之间都是一个空格隔开的
我要将这些数据 不满足4位的在他前面不空格 让他满足4位 用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#代码怎么实现 请指教!
不足的补上就可以了。
if((strA != 4)&&(strA.Length <4))
{
for(int cnt=0;cnt <4-strA.Length;cnt++)
{
if(strA != 4)
{
strA+=" "+strA;
}
}
} 楼主这方面的东西问的不少了,方法也给你说了不少了还有哪不明白???
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);
}
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();
1.txt是原来的文件,2.txt是转换后的文件。
using System.IO;
using System.Collections;List<string> l = new List<string>();using (StreamReader sr = new StreamReader(@"D:\1.txt"))
{
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);
l.Add(s);
}
}File.Delete(@"D:\1.txt");
using (StreamWriter sw = new StreamWriter(@"D:\1.txt", true))
{
foreach (string s in l)
{
sw.WriteLine(s);
}
}
using (StreamReader sr = new StreamReader("TextFile1.txt"))
{
string str = string.Empty;
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
str += line;
}
String[] arrA = str.Split(' ');
for (int i = 0; i < arrA.GetUpperBound(0); i++)
{
while(arrA[i].Length < 4)
{
arrA[i] = " " + arrA[i];
}
}
}