+ 2
How to know if the first letter of a String is alphabetically greater than the first letter of another String?
Hello everyone, Hope you are having a great day so far! I'm fairly new to java and I received an exercise to compare the first characters of two Strings and print Yes if the first character of the first string is alphabetically greater than the second string and No otherwise Eg. (hello, java). this would give me No because h is not alphabetically greater than j. I know that there is some method out there that can assist me with this but I can't seem to find one. All answers are much appreciated!
4 Answers
+ 3
If your first string is in variable named first and second string is in variable named second. You can write this
If(first.charAt(0) > second.charAt(0)){
//Do whatever here
}
+ 1
Thank you Umar!
+ 1
Leo Hunter
But you have to be careful:
first.charAt (0) > second.charAt (0) means not that you compare the letters itself, you compare the ascii values of these letters.
A > b --> true (65 < 98)
a < B --> false (97 > 66)
If you have capital letters in your String, you can use this method: YourString.toLowerCase ();
0
did old java not have an easier way?
char character = 'a'; int ascii = (int) character;
get the specific Character from the String first and then cast it. char character = name.charAt(0); // This gives the character 'a' int ascii = (int) character; // ascii is now 97.
do the next then compare well that how we used to do it lol