efficient way to replace char in StringBuffer

L

Liz

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, ' ');
 
G

Gordon Beaton

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top