3

I have to write a method to compare strings alphabetically and return an int. I can't use any built-in functions and I'm supposed to use a for loop.

I'm unsure about how to deal with the strings being of different lengths. At the moment my main issue is that the code is only comparing the first char of each string then returning the int, but I can't put return comparison; outside of the for loop

public class poop {
    public static int Compare(String s1, String s2) {

       for (int i = 0; i < s1.length() && i < s2.length(); i++) {

           int comparison = 0;
           int ascii1 = 0;
           int ascii2 = 0;
           //convert chars into their ascii values
           ascii1 = (int) s1.charAt(i); 
           ascii2 = (int) s2.charAt(i); 

           //treat capital letters as lower case
           if (ascii1 <= 95) {
               ascii1 += 32;
           } if (ascii2 <= 95) {
               ascii1 += 32;
           }

           if (ascii1 > ascii2) {
               comparison = 1;
           } else if (ascii1 < ascii2) {
                 comparison = -1;
           } else { 
                 comparison = 0;
           }

       } 
       return comparison;
    }

    public static void main(String[] args) {
        String s1 = "aba";
        String s2 = "aaa";
        System.out.println(Compare(s1,s2));
  }
}
4
  • "I can't put return comparison; outside of the for loop"... why not? Commented Oct 24, 2014 at 18:22
  • breakit in if statement, and you could just move return comparison outside of loop Commented Oct 24, 2014 at 18:32
  • Dealt with the comparison, just had to define it outside of the for loop.. Commented Oct 24, 2014 at 18:37
  • If you're supposed to compare two Strings and you can't use any "built-in" functions then you're hosed. You at least would need to use charAt or getChars to access the data. And of course you can't use length to find out how long the String is. Commented Oct 24, 2014 at 20:49

1 Answer 1

4

If you are comparing alphabetically, that means that the first different character in the string defines the difference. For example: aab goes before aac because of the c.

As for different length strings, larger strings go after smaller strings (a dictionary uses that convention). So aaaa goes after aaa, because aaaa is larger.

So, let's get it done:

/**
 * Will return an integer bigger than 1 if s1 is "bigger" than s2
 */
public static int compareStrings(String s1, String s2) {
    int comparison = 0;
    int c1, c2;
    for(int i = 0; i < s1.length() && i < s2.length(); i++) {
        c1 = (int) s1.toLowerCase().charAt(i);   // See note 1
        c2 = (int) s2.toLowerCase().charAt(i);   // See note 1
        comparison = c1 - c2;   // See note 2

        if(comparison != 0)     // See note 3
            return comparison;
    }
    if(s1.length() > s2.length())    // See note 4
        return 1;
    else if (s1.length() < s2.length())
        return -1;
    else
        return 0;
}

Notes:

  1. I use the toLowerCase() method to convert the strings to lower case. If you can't use any "built-in" methods, you can use your conversion (that ASCII += 32 piece). However, you must be careful: You must check that the character value is an alphabetic character before converting them like this (Use google to find an ASCII table and check which are the valid alphabetic character values)
  2. c1 and c2 are integers, so comparison = c1 - c2 will hold the difference between those integers (characters).
  3. If comparison == 0, that means that the characters are equal, so nothing is done. But if comparison != 0, the characters are different; if comparison > 0 that means that c1 is "bigger" than c2, so s1 is larger (look the first paragraph of my answer); if comparison < 0 then s2 is bigger.

    So, if comparison != 0, then you can return its value. Remember: the return sentence does two things: It returns a value and exits the function. So the execution of the for loop is stopped too.

  4. The previous code solves the issue for the minimum string length. But, as posted in your question, you must deal with the case where the strings have different lengths. That last part of the code deals with them (and it can only be reached if comparison is still 0):
    • If s1.lenght() > s2.length(), then s1 is "bigger" than s2, so a positive value (+1) is returned.
    • If s1.lenght() < s2.length(), then s1 is "smaller" than s2, so a negative value (-1) is returned.
    • In any other case, it would mean two things:

      (a) that all the chars of both strings are equal (because comparison == 0), and

      (b) that the length of both strings are equal

      so the strings are equal, and a zero value must be returned.

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

4 Comments

Thanks for the help Barranka although don't fully understand what you did. I can't use any built in functions. However, I solved the issue with another if loop.
@DynoDimo If you've already solved the comparison issue, then take a look to the last part of my code sample; that's the way to deal with different string lengths... Let me edit the code to remove all the comments
@DynoDimo I've added some explanation to my answer... Notes 1 to 3 deal with the minimum length case, and note 4 deals with the different length case (example: abc vs abcabc)
You were right.. I think your example is better and complete than mine.. :) +1 for a concise code

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.