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));
}
}
breakit in if statement, and you could just movereturn comparisonoutside of loopcharAtorgetCharsto access the data. And of course you can't uselengthto find out how long the String is.