the*_*Guy 3 c# string split duplicates
我有一个看起来像这样的文件:
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
.. ...... ...... ...... .. .......
Run Code Online (Sandbox Code Playgroud)
我想string.Split()用来拆分每个字符串,然后检查每一行"string [0]"的第一个值.如果有相同字符串[0]的重复项,我想在字符串[0]的末尾添加一个递增的" - #".所以它会像string[0] + "-i".....
我的意思是,对于L5的在上面的txt文件,他们将被更改为L5-1,L5-2,L5-3.同样适用于P4's(即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
.. ...... ...... ...... .. .......
Run Code Online (Sandbox Code Playgroud)
问题:
如果对于只包含一个匹配项的所有值都为-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]])));
}
}
}
Run Code Online (Sandbox Code Playgroud)
样本输入:
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
Run Code Online (Sandbox Code Playgroud)
样本输出(测试):
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
Run Code Online (Sandbox Code Playgroud)
如果您不想要-1,则可以在写入之前始终进行检查以确保计数> 1.
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |