1

im interested in your experience with c/c++ find, find_first_of, replace, strpos, grep and concat. what is the most efficient method for replacing content in strings.

  • no string replaces appear more than once per string
  • the resulting string will not be the same length as the original.
  • the original and final string will be less thn 2000 chars
  • approximately 25 string replaces
  • the needle remains consistent per haystack

ill test them, simply gathering options at this point.

here is the application at hand: a url string that needs extensive massaging. ie. almost all parameters will change, although the value will remain the same. from

param1=this&param2=string&param3=needs&param4=a&param5=lot ... &param25=work 

to

what=this&method=string&will=needs&work=a&the=lot ... &best=work 

i currently use a needle/haystack function that works on the existing string.

void findAndReplace(string& haystack, const string& needle, const string& replace) { size_t len = needle.size(); if (haystack.size() < len) return; size_t pos = haystack.find(needle); if (pos != string::npos) haystack.replace(pos, len, replace); } 

i dont mind using char*, string, streams, grep or other. and building a new string is also an option.

thanks

6
  • 1
    check out stackoverflow.com/questions/7724011/… and... Commented Jan 14, 2013 at 20:42
  • stackoverflow.com/questions/3895006/… Commented Jan 14, 2013 at 20:42
  • There is really no efficient method to replace string content. The standard operations are: search, allocate new string, replace content. The only efficiency is if you can overwrite rather than insert new text. The efficient method is to not replace or minimize the need to replace. Commented Jan 14, 2013 at 20:55
  • 1
    Part of your work is to simply find the needles in the first place. If you'll be doing a lot of these search operations with a limited set of needles (re-using the same needles over & over again), and if you're really interested in efficiency, you can look into writing your own search function using the BM or BMH algorithms. You'd pre-compute skip tables for each needle, and use the skip tables when searching for each needle. Commented Jan 14, 2013 at 22:02
  • I should have also mentioned that BM & BMH are generally faster only if your needles are longer than some threshold; I'm guessing something like 8 characters. Commented Jan 14, 2013 at 22:40

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.