Real-time search and replacement

I have a file that contains many numbers that I want to mix to create a new file. First, I extract all the text using File.ReadAllText , then split and extract numbers from each line containing a number separated by commas or spaces. After scanning, I replace all occurrences of each found number with a new reduced number, but the problem is that this method is error prone, as some numbers are replaced more than once

Here is the code I'm using:

 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); 

As you can see, the above method is redundant as it does not replace strings in real time. Maybe my head is full, but I'm just lost how to do it. Any ideas?

Thanks.

0
string c # replace
source share
2 answers

I think regex can help here

 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); 
+2
source share

Immediately after entering the question, I realized that the answer is to repeat the character in character and replace accordingly. Here is the code I used to make this work:

 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); 

Comments and / or suggestions for optimization are welcome.

0
source share

All Articles