• Post Reply Bookmark Topic Watch Topic
  • New Topic

Least intensive way to replace string in string?  RSS feed

 
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm going to have to use a String over and over again, maybe 200 times, but replace a part of it with new strings.
So something like this:
String base = "<a href=\"[ref]\">[caption]</a>";
Then in a loop, I might do:

My question is: what's the best way (least amount of object creations, fastest) way to replace a string in a string and concatenate them all together?
 
Ranch Hand
Posts: 1551
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I would do something like -
StingBuffer big = new StringBuffer( 200 * maxSmall );
StringBuffer small = new StringBuffer ();
for ( int i = 0; i < refs.length; i++ ){
small.setLength(0);
small.append( "<a href =" );
small.append( refs[i] );
small.append( caption );
small.append( "<a>" );
big.append( small );
}
 
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm thinking something like

Then repeat for captions. (Not shown.) Sure, that uses two StringBuffers, but it's fairly simple. If you want to use only one StringBuffer, search for [ref] and [caption] simultaneously, and put in extra logic depending on which you find:

You may be able to code something than the regex classes for this case, but I doubt it's worth the trouble. Test and see, I guess...
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim,
I wanted to use the regex stuff, but then I tie myself to 1.4+, since those options aren't available for 1.3 and earlier (unless, are they in an optional package?).
I ended up instead with something similar to your first option instead. Do you think the regex package is as fast as simple indexOf checks and substrings?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Offhand I think that for simple searches/patterns indexOf() will be faster, and for more complex stuff, ummm, it could go either way. E.g if you have ten different tags to search for, I bet a single regex will work better than using indexOf() to look for ten different strings. For just two different tags - dunno, got to test, I guess.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!