efficient way to replace char in StringBuffer  
Author Message
Liz





PostPosted: 2004-8-2 16:42:00 Top

java-programmer, efficient way to replace char in StringBuffer I normally use strings. Just starting to use StringBuffer.
How can I do the following better? (Replace <cr> and <lf>
with <space>)

String s = DynamicPanel.dynamicCmdArea.getText(0, len);
StringBuffer ss = new StringBuffer(s);
int j = -1;
while ((j = ss.indexOf("\n")) != -1)
ss.setCharAt(j, ' ');
while ((j = ss.indexOf("\r")) != -1)
ss.setCharAt(j, ' ');


 
Gordon Beaton





PostPosted: 2004-8-2 16:57:00 Top

java-programmer >> efficient way to replace char in StringBuffer On Mon, 02 Aug 2004 08:42:18 GMT, Liz wrote:
> I normally use strings. Just starting to use StringBuffer.
> How can I do the following better? (Replace <cr> and <lf>
> with <space>)
>
> String s = DynamicPanel.dynamicCmdArea.getText(0, len);
> StringBuffer ss = new StringBuffer(s);
> int j = -1;
> while ((j = ss.indexOf("\n")) != -1)
> ss.setCharAt(j, ' ');
> while ((j = ss.indexOf("\r")) != -1)
> ss.setCharAt(j, ' ');

After replacing a character, there's no need to search again from the
start of the StringBuffer, so at the very least you should use
indexOf(String, fromIndex) to start from the last place you stopped.

If the StringBuffer is long, you might want to do the iteration
manually to avoid having to repeat it for the second set of
replacements:

int len = ss.length();
for (int i=0; i<len; i++) {
switch (ss.charAt(i)) {
case '\n':
case '\r':
ss.setCharAt(i,' ');
}
}

/gordon

--
[ do not email me copies of your followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e