0

I've been given this question of string comparison. I had to write a method to compare two strings without using java's built in string comparison methods. Also it suppose to be around 3 - 5 lines of code long. The method should return 0 for equal, 1 for string 'a' is bigger then string 'b', -1 for string 'a' is smaller then 'b'

Now, I know Java compares string based on the int value of each char so I tried to do this thing, which works but is definitely not 3-5 lines of code long:

public int compare(String s1, String s2){

    int result = 0;
    int count = 0; // The counter for the first string integer values sum
    int count2 = 0; // The counter for the second string integer values sum

    for(int c=0; c<s1.length(); c++){
        count = count +s1.charAt(c);
    }

    for (int c2=0; c2<s2.length(); c2++){
        count2 = count2 +s2.charAt(c2);
    }

    //***** some condition statement to check which is bigger and then return the result
4
  • 1
    The count is not useful for Strings longer than one character. Why don't you compare each character in the String as String does? Commented Jul 16, 2014 at 12:52
  • 3
    Your algorithm is wrong: 'az' is smaller the 'ba', athough the sum of its chars is bigger. Commented Jul 16, 2014 at 12:52
  • Thank you friend, can suggest any other proper solution? Commented Jul 16, 2014 at 13:02
  • it is not a length comparison. The method should be able to determine which string is bigger based on lexicographically values Commented Jul 16, 2014 at 13:11

5 Answers 5

5

Have you considered doing a simple lexicographic comparison rather than comparing lengths (or whatever it is that you try to do, it's not particularly easy to tell):

for(int i=0; i<a.length() && i<b.length(); i++) {
    if(a.charAt(i) != b.charAt(i))
        return a.charAt(i) < b.charAt(i) ? -1 : 1;
}
return a.length() < b.length() ? -1 : a.length() == b.length() ? 0 : 1;

This is basically the same as what java.lang.Strings do except it only uses public methods.

Sign up to request clarification or add additional context in comments.

1 Comment

I will upvote for your solution for the part that I missed in mine a.length() == b.length() ? 0 althought I found it really unfair that mine is downvoted while it's almost the same solution!
0

I think this recursive approach might work for you:

public static int compare(String a, String b, int pos){
    if(a.charAt(pos) == b.charAt(pos) && pos >= a.length() && pos >= b.length())
        return 0;
    else if(a.charAt(pos) > b.charAt(pos))
        return 1;
    else if(a.charAt(pos) < b.charAt(pos))
        return -1;
    else {
        pos++;
        if(pos < a.length() && pos < b.length())
            return compare(a,b,pos);
        else if(pos < a.length() && pos >= b.length())
            return 1;
        else if(pos >= a.length() && pos < b.length())
            return -1;
        else return 0;
    }
}

You have to call the compare method on main with the variable pos at 0 like this:

public static void main(String[] args) {

    String a = "azzz";
    String b = "azz";

    System.out.println("" + compare(a,b,0));
}

Hope this helps.

Comments

0

Here is my try. I tested it a bit and it seems to work. If it doesn't, then sorry. I've got much to learn.

So, my try is based on how Strings are treated in Java, i.e. they are immutable. Any String you create goes into a "Constant String Pool". When you make a new reference to a String that is already in the pool, the JVM makes that reference indicate to the String object that already exists in the pool. So I think it is clear that 2 identical String references are pointing to the exact same String object, even if they have been created separately. Based on this, my method returns 0 if the references are equal and does something else otherwise. Please excuse the return at the end, I know it's ugly, the program won't compile without. I also know(hope) it is unreachable. Here is the function(6 lines):

public int compare(String s1, String s2) {

    if (s1 == s2) return 0;
    else {
        for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) {
            if (s1.charAt(i) > s2.charAt(i)) return 1;
            else return -1;
        }
    }
    return -2;
}

7 Comments

String s1 = "Hello"; String s2 = new String("Hello"); System.out.println(compare(s1, s2)); - I believe that would print -2, as though the Strings are identical, their references wouldn't be.
They don't - try it. Strings created with new String("") aren't immediately interned to the string pool.
It actually prints -1 on mine. A simpler test would be to do System.out.println("Hello" == new String("Hello"));. You'll see that it prints false, because they don't reference the same object.
You could manually call .intern() on each argument during the referential equality check (so s1.intern() == s2.intern()) and then that line would work properly for the example I gave as well.
doesn't intern() use equals() ?
|
0

Considering 2 String a and b a solution might be:

int comp = 0;
for(int i = 0; i < Math.min(a.length(), b.length()); i++) 
    if((comp = a.charAt(i) - b.charAt(i)) != 0)
        return comp;
return a.length() < b.length() ? -1 : a.length() == b.length() ? 0 : 1;

which calculates the difference of every char in the same position upto the smaller String length and if they are all 0 returns the smaller String.

Edit: I don't know the reason for the downvoting might be but anyway on a quick test it works as expected (and it's 5 lines long).

3 Comments

Can please explain the reason for downvoting?
Test your algorithm, and you'll see.
OK I think now is fixed
-2

This should work... (haven't compiled so not 100% sure). I know it isn't < 5 lines but it should work correctly. Can try to shorten it after that.

for(int i=0; i < s1.length(); i++)
{
    if(s2.length()-1 < i)
      return -1;
    if(s1.charAt(i) > s2.charAt(i))
      return -1;
    if(s1.charAt(i) < s2.charAt(i))
      return 1;
}
if(s2.length() > s1.length())
  return 1;
return 0;

17 Comments

Doesn't compile, and is wrong. The length doesn't tell anything about which is lexicographically smaller than the other one: 'aaaaaaa' is smaller than 'z'. The length is only relevant if the bigger string starts with the smaller string.
Misunderstood your question. My apologies.
Still broken. length is a property of arrays, not Strings. You'd need length(). Either way, the point still remains that the OP doesn't want a comparison based upon the length.
This shouldn't compare anything on length. The only times it does is if the same it has the same chars. IE. aaa is smaller than aaaa.
As I said, I didn't compile it... so there could be minor issues like missing parenthesis. Thanks for the suggestion though. Answer edited to add them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.