Java Help! Writing a sorting code, not sure how to start.
write a method called compare1 that takes String s1 and String s2 as arguments and returns an integer. It should compare s1 and s2 alphabetically such as follows: Compare(s1, s2) = 1 if s1 > s2 −1 if s1 < s2 0 otherwise For example, compare(“apple”, “king”) would produce -1. Note that “apple” < ”king”, corresponding to “apple” being closer to the beginning of a dictionary than “king”. You cannot use any built-in Java functions2 for comparing strings for this question. You should use a for loop that compares each character one by one, extracting the characters using the charAt method. Note that you must handle the case where the Strings will have different lengths. You are to treat upper- and lower-case letters as if they were identical (Hint: Use the String methods toUpperCase or toLowerCase). Note that you should handle spaces as being “less than” all other characters. Assume that there are only letters and spaces in the Strings. Examples: • compare("ABC", "abc") gives 0 • compare("hello", "hello world") gives -1 • compare("hello", "hellothere") gives -1 • compare("my very elegant mother", "just sent us nine pickles") gives 1 • compare("hello", "hello ") gives -1
I'm sort of thinking of a direction to take. Using a for loop to loop through every char in the string and compare from there. But I don't know how :(
The key to answering this question is in converting the characters to numerical values.. ``` int a = (int)'a'; int z = (int)'z'; System.out.println(String.valueOf(a) + ", " + String.valueOf(z)); ``` Will print out ``` 97, 122 ``` and everything inbetween is as you would expect. Make your sorting algorithm from there - here's an ascii table of character to numerical values: http://www.asciitable.com/
A couple of other points: If you use the String function charAt(), you can compare them as though they are already converted to ASCII codes, using >, == or < operators. The ascii code for a space is 32, while uppercase characters start at 65, and lowercase at 97, so the space is automatically taken care of by the ascii code. I would implement the toLowerCase() or toUpperCase() function at the beginning of the method. Finally, you need to handle the comparison between "hello" and "hello " (last given example).
Join our real-time social learning platform and learn together with your friends!