John Cena John Cena - 1 month ago 10
Java Question

Comparing Strings without using String.compareTo in Java

Basically, the assignment is being an ass and doesn't want us to use an existing method to compare two strings alphabetically.

It should return 1 if the first string is "bigger" alphabetically than the second (in the sense that 'g' is bigger than 'a'), -1 if the second is bigger, or 0 if they are the same.

Lets say i have

String a = "Cows";
String b = "Horses";


The method should return -1.

My understanding is to use a for() loop to scan both a and b, using charAt(), but I have no idea how to implement this...

EDIT***

reading the answers I've come up with this.

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


The strings being compared all start with uppercase, so it shouldn't be a problem. However, when using the normal String.compareTo() and a bubblesort method that counts the number of times this method was called while sorting a predertermined string array, I get different results, which means something is obviously wrong.

For people viewing this and having the same problem, here's how the code works

int compared = 0;
//program assumes strings are equal

for (int i = 0; i<s1.length() && i<s2.length(); i++){
//for() loop goes on until the largest string
int a = s1.charAt(i);
int b = s2.charAt(i);
//convert char into int for comparison just in case
if(a < b){
compared = -1;
break;
//breaks at the first occurence of non equal characters
}
else if(a > b){
compared = 1;
break;
//same as above
}
}
return compared;

Answer

Without really giving you the answer, given this is homework, I think I can point you in to the right direction.

Your understanding to use a for loop to iterate through the two words is correct, as well as using the String.charAt. Now what I want you to start with is to find the end of your for loop - that is, find out how many characters you should iterate through?

A hint:

'b' > 'a'

This hint has a trap in it though. What should you do, given the following strings?

Haskell

java

A hint for this too:

'A' < 'a'