Using Recursion To Compare Strings To Determine Which Comes First Alphabetically Java

后端 未结 3 1626
旧巷少年郎
旧巷少年郎 2021-01-27 02:25

I am trying to write a method that uses recursion to compare the strings str1 and str2 and determine which of them comes first alphabetically (i.e., according to the ordering us

3条回答
  •  灰色年华
    2021-01-27 03:14

    Make a method int recursiveCompare(String string1, String string2, int index). Initially call it with index = 0. Compare string1.charAt(index) and string2.charAt(index), and if they're different, return 1 or 2. If they're the same, return recursiveCompare(string1, string2, index + 1).

    Of course, you'll have to check the lengths of string1 and string2 before calling charAt(index). If they both reach the end at the same time, they're equal, so return 0. Otherwise, return the number of the one that has ended.

    And yeah, recursion is pretty much the worst way to do this, LOL.

提交回复
热议问题