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

后端 未结 3 1655
旧巷少年郎
旧巷少年郎 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:12

    No recursion required... (Unless this is specifically required in the homework(?) assignement...)

    As this looks a lot like homework, I'll just give a few hints

    Use a integer variable, say i, to index from 0 to the length of shorter string. As long as str1[i] == str2[i], and the last index value hasn't been reached, increment i. If you do reach the last possible value for the index, then the shorter string comes first (or they are deemed equal if same length...)

    Otherwise, compare this first character that differs, and decide which string is first accordingly... Could be as simple as:
    return (str1[i] < str2[i]);

    If recursion you must... (and it was readily said in other comments, this kind of problem is truly not a logical/valid candidate for recursion...)

    The idea is to have a function with this kind of interface:

    int  RecursCompare(string str1, string str2, int i)
    

    and which calls itself, passing the same values for str1 an str2 and passing the next value for i (i+1), as long as str1[i] == str2[i] AND neither str1 or str2 is at its end. When this condidtion becomes false, recursion ends, and instead the function returns the appropriate value to signify tha Str1 is alphabetically before or after Str2.

提交回复
热议问题