Re: Java String Manipulation - Can this be made more efficient?
Man Alive wrote:
Eric Sosman wrote:
Man Alive wrote:
I receive string in a method that always have at least one comma in it:
example:
1) california,sacramento
2)newyork,albany
I need to only extract the first part of the string; i.e. the string
portion before the comma: california, newyork
Currently, it is coded like this (stringName is the string being
examined):
int commaLocation = stringName.indexOf(",");
int stringLengthBeforeComma = (stringName.length() - (commaLocation
+1));
System.out.Println("Part of String before comma: "
+stringName.substring(0,stringLengthBeforeComma));
Before worrying about efficiency, worry about correctness.
By coincidence this fragment works for "california,sacramento",
but it will fail on "newyork,albany" or "ohio,columbus" or
"massachusetts,boston". Try them and see!
... and then, after you've fixed it, I'd guess that you
could gain a little speed with indexOf(',') instead of
indexOf(","), but there won't be much improvement beyond that.
Eric:
I could not catch the flaw you mentioned above, it works for all the
permutations listed.
Have I missed sometime?
Well, it's possible I've goofed (it happens ...). Let's
see [copy-and-past posted code into NetBeans, add a little
scaffolding, toss lightly with extra virgin olive oil and
balsamic vinegar] No; I was right. For the String values
"california,sacramento", "newyork,albany", "ohio,columbus",
and "massachusetts,boston", I get the outputs "california",
"newyor", "ohio,col", and "massac", respectively.
One thing I noticed, though, that I'd overlooked before:
The code you posted has no hope of compiling, because the
System.out object has no Println() method. So "it" can't
possibly be what "works for all the permutations;" anything
that does so must be some other "it." Have you been guilty
of asking about code that isn't the code you posted, hmmmm?
I can't (usually) debug what I can't see.
--
Eric.Sosman@sun.com