日期:2014-05-17  浏览次数:20848 次

C#循环替换的问题。代码该怎么写
现有一文本,里面内容大致为

10000
10000
10000
10000


想要替换为

10001
10002
10003
10004

注意,是替换,不是生成。
代码该怎么写啊

------解决方案--------------------
C# code


            string[] lines = File.ReadAllLines("读取文件路径");
            for (int i=0; i < lines.Length;i++)
            {
                lines[i] = (int.Parse(lines[i]) + i+1).ToString();
                Console.WriteLine(lines[i]);
            }

            File.WriteAllLines("写入文件路径",lines);

------解决方案--------------------
C# code
string pattern_line = @"(?<=\d+?)\d(?=\s|$)";
            string[] text_lines = File.ReadAllLines(@"C:\Users\M\Desktop\Test.txt", Encoding.GetEncoding("GB2312")).Select((a, i) => {
                a = Regex.Replace(a, pattern_line, (i + 1).ToString());
                return a; 
            }).ToArray();//读取并替换
            File.WriteAllLines(@"C:\Users\M\Desktop\Test.txt",text_lines);//写回txt

------解决方案--------------------
C# code
        int counter = 1;
        string s = File.ReadAllText((@"c:\test.txt"));
        string r = Regex.Replace(s, @"(?m)\d+", delegate(Match match)
        {
            int value = int.Parse(match.Value) + counter++;
            return value.ToString();
        });
        File.WriteAllText((@"c:\test.txt"), r);

------解决方案--------------------
C# code
string[] text_lines = File.ReadAllLines(@"C:\Documents and Settings\Administrator\桌面\Test.txt", Encoding.GetEncoding("GB2312")).Select((a, i) =>
        {
            a = a.Replace("@",(i + 1).ToString());
            return a;
        }).ToArray();//读取并替换
        File.WriteAllLines(@"C:\Documents and Settings\Administrator\桌面\Test.txt", text_lines);//写回txt