| Author |
Custom String converter.
|
Raghu Devatha
Ranch Hand
Joined: Feb 10, 2009
Posts: 39
|
|
Hi,
I was doing an exercise and wanted to know if my code is efficient.
Input="aaabbaccaab"
Expected Output=a3b2a1c2a2b1
I hope there is a better program.
|
dR
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
Your program looks OK. Are you unhappy with it, and is there a specific thing in the code that you are unhappy with? Can you explain what that is?
One small change would be to use StringBuilder instead of StringBuffer - StringBuilder is a newer version of StringBuffer that doesn't have unnecessary synchronization. You will not notice any speed difference from making that change though in such a small and simple program.
In line 16, you could write counter++; instead of counter = counter + 1; but that doesn't make the code any more efficient.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Raghu Devatha
Ranch Hand
Joined: Feb 10, 2009
Posts: 39
|
|
Thanks Jesper.
When I showed it to my instructor his first impression was I was using too many variables (increasing memory footprint). I was trying to reduce the number of variables used without loosing the readability.
Thanks again for the information on StringBuilder.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Don't use toCharArray() and tempOut, use String's own length() and charAt(int) methods. That way, you don't need to copy the entire String's contents into a new char[]. Because that's what toCharArray() does.
Now, about the number of variables:
- input: you'll need it. That's the String to convert.
- store: you'll need it. How else can you determine when to start a new counter?
- tempOut: you can get rid of this because of my above statement.
- i: you'll need it. It's the loop counter.
- counter: you'll need it. How else can you determine how many times a character occurred?
- result: you'll need it.
So apart from tempOut you can't get rid of any of the variables.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Raghu Devatha
Ranch Hand
Joined: Feb 10, 2009
Posts: 39
|
|
|
Thanks a lot Rob for you expert opinion. It really helps.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
For your information, as a little exercise for myself I rewrote your code using a nested loop. Unless I do not cache c (my version of "store") I still have the same number of variables at 5.
In this code, "c" is the equivalent of "store" and your "counter" is equivalent to "j - i". My code only has one advantage over yours - it can handle empty Strings. For the rest there isn't much difference.
|
 |
 |
|
|
subject: Custom String converter.
|
|
|