2012-09-08 176 views
0

我有一个文件,其中包含大量的数字,我想减少构建一个新的文件。首先,我使用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); 

正如你所看到的,上面的方法是多余的,因为它不能实时替换字符串。也许我的头已满,但我对如何解决这个问题感到失落。有任何想法吗?

谢谢。

回答

2

我认为,正则表达式可以帮助这里

string text = File.ReadAllText(file); 
string newtext = Regex.Replace(text, @"\b(([0-9]+)?\.)?[0-9]+\b", m => 
    { 
     float f; 
     if (float.TryParse(m.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out f)) f *= 3.0f/4; 
     return f.ToString(); 
    }); 
File.WriteAllText(file, newtext); 
+0

高超,比我更快。谢谢 –

0

刚刚输入问题后,我意识到答案是逐个字符地迭代并相应地进行替换。这里是我用来得到它的代码:

string nfar = ""; 
var far = File.ReadAllText("paths.js"); 
bool neg = false; 
string ccc = ""; 
for(int i = 0; i < far.Length; i++) 
{ 
    char c = far[i]; 
    if (Char.IsDigit(c) || c == '.') 
    { 
     ccc += c; 
     if (far[i + 1] == ' ' || far[i + 1] == ',') 
     { 
      ccc = neg ? "-" + ccc : ccc; 
      float di; 
      if (float.TryParse(ccc, out di)) 
      { 
       nfar += (di*0.75f).ToString(); 
       ccc = ""; 
       neg = false; 
      } 
     } 
    } 
    else if (c == '-') 
    { 
     neg = true; 
    } 
    else 
    { 
     nfar += c; 
    } 
} 
File.WriteAllText("nfile.js", nfar); 

欢迎评论和/或优化建议。