• Post Reply Bookmark Topic Watch Topic
  • New Topic

String problem  RSS feed

 
Meyer Florian
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey there!
Simple question... I've got a string and I want to replace all " " (double or multiple spaces) with " " (one single space). My only solution is:
while(myString.indexOf(" ") != -1) {
myString = string.trim().replaceAll(" "," ");
}
Do you know any better or more efficient solution?
Thanks in advance
Praiser
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You don't need the while statement, or even an if, because the replaceAll() will perform this check for you as it looks for things to replace. If it doesn't find anything, it won't do any work, and will simply return the same string it started with.
As for the " ++" - this is a regular expression which grabs as many consecutive spaces as it can at a time (at least one), and doesn't waste time backtracking. (In practice I think " +" would perform about the same here, but I like using posessive quantifiers be default.) Many people don't realize that the first argument of replaceAll() actually uses regex, but it does. It's worthwhile to spend some time learning regex if you haven't.
It's also possible you might create a custom method which is more efficient than using the regex engine (which is after all designed as a general-purpose sort of thing, and may not be optimized for this particular search). But I really doubt it would be worth the trouble; you may create something slightly faster, but a lot longer and more complex.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!