How to compare strings of characters in Java?
October 17, 2011 – 4:00 pmI am new at Java and at a lost, I need to compare two strings of characters in java to find which one comes first in the alphabet and don’t know where to start. Any suggestions where I can start? Any and all help would be appreciated.
Thank you so much.
Also can you have more than one compareTo in a program? I need it for two methods but the first methods results will override the second even if I do not initiate the first method.
Related posts:
- What is the best way to compare 2 strings named string1 and string2 in an if statement in java?
- Can somebody please help me learn to use Java strings for a Mad Libs program?
- I need help writing a java method that returns how many times two consecutive characters occur in a string.?
- How do I create a simple Java file that reads in characters then outputs them again, one by one?
- How do I create a simple Java file that reads in characters then outputs them again, one by one?
- How can I include special characters in Java?
- The provision made in Java for manipulating individual characters?
- How do you compare generic objects in Java?
- python programming – splitting strings into its component characters?
- Is there an Eclipse plugin to translate all strings from english to spanish? Java?
3 Responses to “How to compare strings of characters in Java?”
Bconvert the string into a String[] (string array) then compare the array piece by piece with the string being compaired
By William on Oct 17, 2011
Try str.compareTo().
I don’t think == works, as that compares the object reference, not the string contents.
By michaeljhuman on Oct 17, 2011
A sort is one line of code in Java if we are using Objects that implement the .compareTo() interface. I suppose this is an academic exercise.
public class CompareStringByChars {
public static void main( String[] args ) {
String t1 = "ghbnxmbb";
String t2 = "ghbnz";
String longest = "";
longest = t1.length() >= t2.length() ? t1 : t2;
System.out.println("longest.len: " + longest.length());
String shortest = "";
shortest = longest.equalsIgnoreCase(t1) ? t2 : t1;
String result = "";
int count = 0;
do {
result = shortest.charAt( count ) < longest.charAt(count) ?
shortest : longest;
} while( ++count < shortest.length());
System.out.println("First String is: " + result);
System.out.println("2nd String is: " +
(result.equalsIgnoreCase(shortest) ?
longest : shortest) );
}
}
By deonejuan on Oct 17, 2011