I have an annoying problem with replacing in C#. I have an array with what letter i should to replace with:
string[] replaceLines = format.Replace("n", "").Split(new char[] { '=', ',' });
That’s basically a file output that splits to array
Next a have this loop:
for (var i = 0; i < replaceLines.Length - 1; i = i + 2) { json = Regex.Replace(json, replaceLines[i], replaceLines[i + 1]); }
That should replace it right, according to the JS
function replace() { let area1 = document.querySelector("#text1").value; let area2 = document.querySelector("#text2").value.replaceAll("n", "").split(/[=,]/g); console.log(area2); for(let i = 0; i < area2.length - 1; i = i + 2) { area1 = area1.replaceAll(area2[i], area2[i + 1]); } document.querySelector("#text1").value = area1; }
<!DOCTYPE html> <html> <head> <title>BB+ sheeesh</title> <meta charset="utf-8"> <link rel="shortcut icon" href="atom.io/favicon.ico"> <link rel = "stylesheet" href="style.css"> <style> table { color:deepskyblue } </style> </head> <body> <script src="script.js"></script> <h1>Input</h1> <textarea id="text1" cols="160" rows="12"></textarea> <h1>Replace pattern (example: n=r, and new line, if adding more)</h1> <textarea id="text2" cols="160" rows="12"></textarea> <br> <button onclick="replace()">Change</button> </body> </html>
Can you help me re-writing this exact thing but with C#? I don’t know what to do, i have tried string.Replace as well
Advertisement
Answer
Potential cause of the issue your seeing in c# is your line endings. On windows they will not be "n"
they will probably be "rn"
So I’d suggest using Environment.NewLine
as it should automatically adjust to the environment you’re running on.
Also, unless you’re wanting to parse regex in your replacement swap Regex.Replace()
, with "string".Replace()
in your loop. Regex will probably do what you want it to do, but the Regex engine isn’t necessary by the looks of it.
I’ll also note, this seems to be a bare-bones replacement script. It’d be smart to validate your pattern strings.
how it’s written you could potentially replace items unintentionally, for instance, if you used a=b,b=c
, all a
‘s would become c
‘s and you’d be left with no b
‘s
Another assumption being made is there will be a comma separating each replacement pairing, so as is if you had a paring such as:
@"a=b c=d"
you’re array would end up being ["a","bc,"d"]
instead of: ["a","b","c","d"]