Home > Java > Implementing a fast method for cleaning arrays returned as Strings

Implementing a fast method for cleaning arrays returned as Strings

In the article of 30.1.10 on String Sorts I talked about a means of cleansing an array returned as a String by using for illustrative purposes one which had the somewhat iffy method name of “topAndTail” and which acts using Strings rather than a StringBuffer, e.g. so that when you return your array via .toString() you end up with output that looks like:

[ a, b, c, d, e ]

which you want back as plain-text

a b c d e

I mentioned that there was a more efficient way of doing this via a StringBuffer. Typically I would implement this StringBuffer-acting method as follows:

public String fastTopAndTail(String toDo)
{
StringBuffer sb = new StringBuffer(toDo);
sb.replace(0, 1, ""); // kill the first [
int k = sb.length();
sb.replace(k - 1, k, ""); // last [ killed
k = sb.length();
for (int i = 0; i < k; i++)
{
if(sb.charAt(i) == ',')
{
sb.replace(i,i + 1,"");
k = sb.length(); 
}
}
return sb.toString();
}

It’s doing exactly the same work as the earlier example topAndTail method but will run a lot faster under a heavy load since it isn’t making lots of copies of String objects. BTW, the call to keep the variable k up to date in the loop is redundant here & you’re welcome to rip it from your copy without expecting adverse effects but by default I like to keep a handle on the k value since many of my StringBuffer methods have a very similar structure and often the char is not being replaced but deleted or added to. If, however, this were production code it would go 🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: