The Artima Developer Community
Sponsored Link

Java Answers Forum
Leftmost Characters

11 replies on 1 page. Most recent reply: Mar 22, 2004 3:43 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 11 replies on 1 page
Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Leftmost Characters Posted: Mar 10, 2004 5:16 AM
Reply to this message Reply
Advertisement
I have a method which is passed a String of arbitary length. I need to store the leftmost three characters. Unfortunately, the String's substring method throws an error if I ask from three characters from a shorter String, so I have come up with the following (which seems somewhat ugly):
this.value = newValue.trim().substring(0, Math.min(newValue.length(), 3));
Is there a simpler/more elegant single line solution that I have missed?

Vince.


twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Leftmost Characters Posted: Mar 10, 2004 5:40 AM
Reply to this message Reply
> I have a method which is passed a String of arbitary
> length. I need to store the leftmost three characters.
> Unfortunately, the String's substring method throws an
> n error if I ask from three characters from a shorter
> String, so I have come up with the following (which seems
> somewhat ugly):
>
this.value = newValue.trim().substring(0,
> Math.min(newValue.length(), 3));
Is there a
> simpler/more elegant single line solution that I have
> missed?
>
> Vince.

Yours is essentially the same solution that I would have come up with. It will be interesting to see if anyone else comes up with something significantly different.

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Leftmost Characters Posted: Mar 10, 2004 5:51 AM
Reply to this message Reply
> > ugly):
> >
this.value = newValue.trim().substring(0,
> > Math.min(newValue.length(), 3));
Is there a
> > simpler/more elegant single line solution that I have
> > missed?
> >
> > Vince.
>
> Yours is essentially the same solution that I would have
> come up with. It will be interesting to see if anyone
> else comes up with something significantly different.

I've just found a bug in my own solution. It fails because it trims the string when extracting characters but not when checking the string length, thus " AB" has a length of three but "AB".substring(0, 3) fails. I should have written:
this.value = newValue.trim().substring(0, Math.min(newValue.trim().length(), 3));
(Now it's even uglier!)

Vince.

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Leftmost Characters Posted: Mar 10, 2004 6:42 AM
Reply to this message Reply
Version 3. Ugliest yet!

Also failed if newValue was null...

this.value = newValue == null ? "" : newValue.trim().substring(0,Math.min(newValue.trim().length(), 3));


Vince.

James Tikalsky

Posts: 12
Nickname: jt2190
Registered: Dec, 2003

Re: Leftmost Characters Posted: Mar 10, 2004 9:37 AM
Reply to this message Reply
Can you make this into a method? Do you have to do everyting in one line?

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Leftmost Characters Posted: Mar 10, 2004 1:33 PM
Reply to this message Reply
> Can you make this into a method? Do you have to do
> everyting in one line?

I already have:
private String leftmost(String s, int n)
{
    return s == null ? "" : s.trim().substring(0, Math.min(s.trim().length(), n));
}


But it doesn't get around the fact that it's an ugly bit of code for something so simple. In VB, the equivalent code would be:
value = "" & Trim(Left(s, 3))
I just felf sure Java could do it more elegantly too.

V.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Leftmost Characters Posted: Mar 10, 2004 1:42 PM
Reply to this message Reply
And in Python the equivalent would be:

value = s[:3]

(so maybe throw a bit of Jython into your Java!)

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Leftmost Characters Posted: Mar 11, 2004 2:31 AM
Reply to this message Reply
I knew Python would have it sussed but I couldn't be bothered to get my Python book out and see what it does. (Does it work if s is null, too.

I did start learning the language last year but found that it was the straw that broke the camel's back when also trying to get my head simultaneously around more advanced Java, EJBs, Weblogic servers, eclipse, Amadeus, TPF, CVS and Ant. (Thankfully, no GUIs to contend with at the moment.)

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Leftmost Characters Posted: Mar 11, 2004 9:01 AM
Reply to this message Reply
If you want to also deal with null, then you'd have to first decide what you want in that case. If s is None (Python's null), then s[:3] will throw a TypeError, since it isn't subscriptable.

In Python, you wouldn't do this in a separate function, since it is so clean and simple. Therefore, I would guess you'd already have enough context to know that s isn't None. For example, if you were reading lines from a file, it might look like this:
for line in file(filename):
   firstThree = line[:3]
   ...

You'd know that you won't get a None result. However, if, for some reason, you really couldn't be sure, you'd just have to first check for None, or catch that exception, whichever style suits your fancy.

By the way, getting a slice from the middle or the end of a collection (or string) in Python outshines Java (and similar languages) even more than getting the first few.

Hagrid

Posts: 4
Nickname: hagrid
Registered: Sep, 2003

Re: Leftmost Characters Posted: Mar 19, 2004 3:36 AM
Reply to this message Reply
I would make a utility method as follows:

/** @return null when s is null */
public static String safeLeftMost(String s, int numChars) {
   return s == null ? null : s.length() <= numChars ? s : s.substring(0, numChars);
}


And call this method with:

// TODO: handle null value better
this.value = newValue==null ? null : safeLeftMost(newValue.trim(), 3);


Note that we have separated the trimming from the left-most functionality, so we can easily remove the trimming when it's not needed anymore.

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Leftmost Characters Posted: Mar 22, 2004 5:32 AM
Reply to this message Reply
> I would make a utility method as follows:
> :
> And call this method with:
> :
> Note that we have separated the trimming from the
> left-most functionality, so we can easily remove the
> trimming when it's not needed anymore.

I've already coded a similar leftmost(String s, int n) method into my app and call it from a number of places. I'd take issue with the detail of your implementation though.

The suggested technique for calling the new method is almost as long as the line that was encapsulated in the new method. I think that this somewhat defeats the objective. Not only does it duplicate some of the code within the called method but that duplicated code (plus the separated out code) has itself to be duplicated each time the method is called. The justification given is "we can easily remove the trimming when it's not needed anymore"... except that we can't because the trims would now be coded at several locations.

Perhaps what is required is:
public static String safeLeftMost(String s, int numChars) {
   return s == null ? null : s.length() <= numChars ? s : s.substring(0, numChars);
}
 
safeLeftMost(String s, int numChars, boolean preTrim)
{
   return s == null ? null : pretrim ? safeLeftMost(s.trim(), n) : safeLeftMost(s, n);
}
 
// Call example.
this.value = safeLeftMost(newValue, 3, true);
All our solutions (and there are plenty of other possible ones) have numerous pros and cons. My main point is that common thread between them is that - given the apparent simplicity of the original problem - they are, none of them, 'elegant'. The complexity of the solutions do not match the simplicity of the problem.

Vince.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: Leftmost Characters Posted: Mar 22, 2004 3:43 PM
Reply to this message Reply
> The complexity of the solutions do not match the simplicity of the problem.

Java certainly has its strengths, but simple string manipulation is not one of them.

This is why it is so important not to be a one-trick-pony with respect to programming languages.

Flat View: This topic has 11 replies on 1 page
Topic: MouseListener freezing up the repaint() Previous Topic   Next Topic Topic: Classpath Question

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use