我有一个看起来像这样的文件:
R.D. P.N. X Y Rot Pkg
L5 120910 64.770 98.425 180 SOP8
P4 120911 -69.850 98.425 180 SOIC12
L10 120911 -19.685 83.820 180 SOIC10
P4 120911 25.400 83.820 180 0603
L5 120910 62.484 98.425 180 SOP8
L5 120910 99.100 150.105 180 SOP8
.. ...... ...... ...... .. .......
我想使用 string.Split()
拆分每个字符串,然后在每一行检查“string[0]”的第一个值。如果有相同字符串 [0] 的重复项,我想在字符串 [0] 的末尾添加一个递增的“-#”。所以它会像 string[0] + "-i"
.....
我的意思是,对于上面.txt 中的L5
,它们将更改为L5-1
、L5-2
,L5-3
。 P4
(即P4-1
、P4-2
)也是如此......
所以新的 .txt 看起来像这样:
R.D. P.N. X Y Rot Pkg
L5-1 120910 64.770 98.425 180 SOP8
P4-1 120911 -69.850 98.425 180 SOIC12
L10 120911 -19.685 83.820 180 SOIC10
P4-2 120911 25.400 83.820 180 0603
L5-2 120910 62.484 98.425 180 SOP8
L5-3 120910 99.100 150.105 180 SOP8
.. ...... ...... ...... .. .......
问题:
- 我怎样才能做这样的事情?
- 对了解如何执行此操作有任何帮助吗?
最佳答案
如果您可以接受所有只包含一次出现的值的 -1,这里有一个示例程序。你必须在最后做一份副本,因为你不能在写入新文件时删除原始文件。
// Replace c:\temp\temp.txt with you original file.
// Replace c:\temp\temp2.txt with your temporary new file.
using (var r = new StreamReader(@"c:\temp\temp.txt"))
{
using (var w = new StreamWriter(@"c:\temp\temp2.txt"))
{
string line;
var counter = new Dictionary<string, int>();
// write header first, no changes necessary
if ((line = r.ReadLine()) != null)
{
w.WriteLine(line);
}
while ((line = r.ReadLine()) != null)
{
// assuming it is safe to split on a space
var values = line.Split(' ');
// if the value hasn't been encountered before, add it
if (!counter.ContainsKey(values[0]))
{
// start counter at 0
counter.Add(values[0], 0);
}
// increment the count as we hit each occurrence of the
// given key
counter[values[0]] = counter[values[0]] + 1;
// write out the original line, replacing the key with the
// format key-#
w.WriteLine(line.Replace(values[0],
string.Format("{0}-{1}",
values[0],
counter[values[0]])));
}
}
}
示例输入:
R.D. P.N. X Y Rot Pkg
L5 120910 64.770 98.425 180 SOP8
P4 120911 -69.850 98.425 180 SOIC12
L10 120911 -19.685 83.820 180 SOIC10
P4 120911 25.400 83.820 180 0603
L5 120910 62.484 98.425 180 SOP8
L5 120910 99.100 150.105 180 SOP8
示例输出(已测试):
R.D. P.N. X Y Rot Pkg
L5-1 120910 64.770 98.425 180 SOP8
P4-1 120911 -69.850 98.425 180 SOIC12
L10-1 120911 -19.685 83.820 180 SOIC10
P4-2 120911 25.400 83.820 180 0603
L5-2 120910 62.484 98.425 180 SOP8
L5-3 120910 99.100 150.105 180 SOP8
如果您不想要 -1,您始终可以在写入前进行检查以确保计数 > 1。
关于C# - 重复修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6751330/