-1

I am trying pass two strings to a function and I want to return the length of the string that comes first lexicographically.

This is what I have tried so far:

public static int problem4(String s, String t) {
    for (int i = 0; i < s.length() &&
            i < t.length(); i++) {
        if ((int) s.charAt(i) ==
                (int) t.charAt(i)) {
            continue;
        } else {
            return (int) s.length() -
                    (int) t.length();
        }
    }

    if (s.length() < t.length()) {
        return (s.length() - t.length());
    } else if (s.length() > t.length()) {
        return (s.length() - t.length());
    }

    // If none of the above conditions is true, 
    // it implies both the strings are equal 
    else {
        return 0;
    }
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Banan
  • 23
  • 4
  • 3
    Where's your attempt at solving the problem? We are not going to do your job for you, but we can help you if you have tried something and it doesn't work as expected. Please read [ask] and provide a [mre]. – JustAnotherDeveloper Oct 06 '20 at 12:42
  • 2
    Remember to be kind even if people tend to think that SO is a "do the job for me" kind of site. – Philippe B. Oct 06 '20 at 12:48
  • sorry for asking a poor question, it was my first time using the site. I will provide my work next time. Sorry – Banan Oct 06 '20 at 12:55
  • 1
    `return s.compareTo(t) == -1 ? s.length() : s.compareTo(t) == 1 ? t.length() : s.length();` – Eritrean Oct 06 '20 at 12:55

2 Answers2

2

You can set them into an array, and use Arrays.sort(). Then retrieve the first item like so:

public static int problem4(String s, String t) {
    String[] items = new String[2];
    items[0]=s;
    items[1]=t;
    items.sort();
    return items[0].length();
    
}

Or you can use the .compareTo method like so:

public static int problem4(String s, String t) {
    return s.compareTo(t) > 0 ? t.length() : s.length();
 }
Philippe B.
  • 485
  • 4
  • 18
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Something to this effect should work I think.

public static int problem4(String s, String t){
    if (s.compareTo(t)>0)
        System.out.println(t.length());
        return t.length();
    else 
        System.out.println(s.length());
        return s.length();
}

problem("a", "b");
hayden_rear
  • 36
  • 1
  • 4