How to compare strings of characters in Java?

October 17, 2011 – 4:00 pm

I 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:

  1. What is the best way to compare 2 strings named string1 and string2 in an if statement in java?
  2. Can somebody please help me learn to use Java strings for a Mad Libs program?
  3. I need help writing a java method that returns how many times two consecutive characters occur in a string.?
  4. How do I create a simple Java file that reads in characters then outputs them again, one by one?
  5. How do I create a simple Java file that reads in characters then outputs them again, one by one?
  6. How can I include special characters in Java?
  7. The provision made in Java for manipulating individual characters?
  8. How do you compare generic objects in Java?
  9. python programming – splitting strings into its component characters?
  10. Is there an Eclipse plugin to translate all strings from english to spanish? Java?
  1. 3 Responses to “How to compare strings of characters in Java?”

  2. 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

  3. Try str.compareTo().

    I don’t think == works, as that compares the object reference, not the string contents.

    By michaeljhuman on Oct 17, 2011

  4. 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

Sorry, comments for this entry are closed at this time.