I hoping for some pointers on the quickest way to do a replace when the document that needs bits replacing is constant (a sort of mailmerge scenario).
Of course there are lots of ways of doing replaces using string.replace and regexp but it looks like they need to开发者_如何学Go parse the input document each time looking for the match. That's the bit I'm trying to optimise.
I'd say your best bet would probably be to split the document into an array with each element being the text that's in between the previous replacement and the next. Then instead of replacing, you simply interleave the contents of your split array with each of the replacement tokens using string concatenation.
Some pseudocode:
doc_array = split(input_doc, "token marker")
for each replace_array in set_of_replace_arrays:
this_doc = ""
while elements remain in doc array:
this_doc.concat(next doc element)
if any elements remain in replace array:
this_doc.concat(next replace element)
output this_doc
For increased flexibility, you could use a XslCompiledTransform and have it output text. It's optimized for fast XML and text generation, and you could include some logic too if required.
Well, as you don't want to parse and your input document is constant, you could use a MemoryStream
to handle your original document and change your bits by using their absolute position.
Another way could be use that String.Format
markers as placeholders:
string input = "Dear {0} {1}";
//...
return String.Format(input, "Mr.", "Farias");
精彩评论