user3288476
user3288476

Reputation: 13

How to find if a string is in range of a given string

I am trying to write an if statement to find out whether the given postal code (zip code) is in the range of 2 given zip codes.

For example, I want to know how to find if J8Q is in the range of J8P-J9A (in this case it is)

I have written this:

public boolean postCodeInRange(String postCode, String zone)
{
    if (zone.charAt(0)==postCode.charAt(0))
    {
        if ((int) postCode.charAt(1) >= (int) zone.charAt(1) &&
            (int) postCode.charAt(1) <= (int) zone.charAt(5) && 
            (int) postCode.charAt(2) >= (int) zone.charAt(2) &&
            (int) postCode.charAt(2) <= (int) zone.charAt(6))

           return true;
    }
    return false;
}

This only works for zip codes like L4J in L0A-L9Z range.

Upvotes: 1

Views: 976

Answers (3)

Vlad Schnakovszki
Vlad Schnakovszki

Reputation: 8601

Your if statement is wrong. You should do it like this:

public boolean postCodeInRange(String postCode, String zone)
{
    if (zone.charAt(0)==postCode.charAt(0))
    {
        if ((int) postCode.charAt(1) < (int) zone.charAt(1) ||
            (int) postCode.charAt(1) > (int) zone.charAt(5)
            return false;
        if (((int) postCode.charAt(1) == (int) zone.charAt(1) &&
            (int) postCode.charAt(2) < (int) zone.charAt(2)) ||
           ((int) postCode.charAt(1) == (int) zone.charAt(5) &&
            (int) postCode.charAt(2) > (int) zone.charAt(2)))
            return false;
        return true;
    }
    return false;
}

As you see, it is very hard to read and even harder to edit. A better solution would be:

public boolean postCodeInRange(String postCode, String zone)
{
    String minCode = zone.substring(0, 3);
    String maxCode = zone.substring(4, 7);
    return minCode.compareTo(postCode) <= 0 && postCode.compareTo(maxCode) <= 0;
}

Upvotes: 0

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

Simple solution :

public boolean postCodeInRange(String postCode, String zone) {
    return postCode.compareTo(zone.substring(0, 3)) >= 0 
        && postCode.compareTo(zone.substring(4)) <= 0;
}

Upvotes: 0

user1097048
user1097048

Reputation:

compareTo method returns the difference of the first different characters between two strings. I am not sure if post codes are always letter-digit-letter but if this is the case it should work. If it is not, you might need a compartor to suit your problem

Basically you should check if input string is between two other strings.

if(minPostCode.compareTo(input) <= 0 && maxPostCode.compareTo(input) >= 0) {
    //it is between two post codes
}

Upvotes: 1

Related Questions