我有一个文件,其中包含大量的数字,我想减少构建一个新的文件。首先,我使用File.ReadAllText
提取所有文本,然后从每行中分离并提取数字,其中包含用逗号或空格分隔的数字。扫描结束后,我替换每个发现号所有出现的新的数量减少,但问题是,这种方法很容易出错,因为一些数字被替换不止一次实时搜索并替换
更下面是我使用的代码:
List<float> oPaths = new List<float>();
List<float> nPaths = new List<float>();
var far = File.ReadAllText("paths.js");
foreach(var s in far.Split('\n'))
{
//if it starts with this that means there are some numbers
if (s.StartsWith("\t\tpath:"))
{
var paths = s.Substring(10).Split(new[]{',', ' '});
foreach(var n in paths)
{
float di;
if(float.TryParse(n, out di))
{
if(oPaths.Contains(di)) break;
oPaths.Add(di);
nPaths.Add(di * 3/4);
}
}
}
}
//second iteration to replace old numbers with new ones
var ns = far;
for (int i = 0; i < oPaths.Count; i++)
{
var od = oPaths[i].ToString();
var nd = nPaths[i].ToString();
ns = ns.Replace(od, nd);
}
File.WriteAllText("npaths.js", ns);
正如你所看到的,上面的方法是多余的,因为它不能实时替换字符串。也许我的头已满,但我对如何解决这个问题感到失落。有任何想法吗?
谢谢。
高超,比我更快。谢谢 –