使用递归比较字符串来确定哪个按字母顺序排在最前面 Java [英] Using Recursion To Compare Strings To Determine Which Comes First Alphabetically Java

查看:52
本文介绍了使用递归比较字符串来确定哪个按字母顺序排在最前面 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种方法,该方法使用递归来比较字符串 str1 和 str2 并确定它们中的哪一个按字母顺序排在最前面(即,根据字典中单词的排序).

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 used for words in a dictionary).

如果 str1 按字母顺序排在第一位,则该方法应返回 int 1.

If str1 comes first alphabetically, the method should return int 1.

如果 str2 按字母顺序排在第一位,则该方法应返回 int 2.

If str2 comes first alphabetically, the method should return the int 2.

如果两个字符串相同,方法应该返回int 0.

If the two strings are the same, the method should return the int 0.

我知道 Java API 中有一个 compareTo 方法,但我想知道如何在没有这个的情况下做到这一点

I know that there is a compareTo method in the Java API but i would like to know how to do this without this

这是我到目前为止所拥有的,但我不完全确定如何进行

This is what i have so far but i'm not entirely sure how to proceeded

 } if (str1.length().equals(str2.length()))

         return 0;
    } else {
        (str.substring(1, str.length()));

任何想法将不胜感激

推荐答案

创建一个方法int recursiveCompare(String string1, String string2, int index).最初用 index = 0 调用它.比较 string1.charAt(index)string2.charAt(index),如果它们不同,则返回 1 或 2.如果它们是相同的,返回 recursiveCompare(string1, string2, index + 1).

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

当然,您必须在调用charAt(index) 之前检查string1 和string2 的长度.如果它们同时到达终点,则它们相等,因此返回0.否则,返回已结束的编号.

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.

这篇关于使用递归比较字符串来确定哪个按字母顺序排在最前面 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆