简体   繁体   English

在 java 中使用递归来反转字符串

[英]Reverse a string using recursion in java

I want to reverse a whole String .我想反转整个String For example, "Cat is running" should give output "running is cat".例如,“Cat is running”应该给 output “running is cat”。

I have tried a lot but I am unable to do it.我已经尝试了很多,但我无法做到。 It shows "gninnur si taC".它显示“gninnur si taC”。 Kindly help me that it should take "cat" as a single character instead of taking 'c' as a single character.请帮助我,它应该将“cat”作为单个字符,而不是将“c”作为单个字符。

Here is the code:这是代码:

public static void main(String[] args) {
    String str = "Cat is running";
    System.out.println("Before recursion: " + str);
    System.out.println("After recursion: " + reverse(str));
}

public static String reverse(String str) {
    if(str.isEmpty())
        return str;

    String s = "";
    for(int i = 0; i < str.length(); i++) {
        s = s + str.charAt(i);
    }
    return reverse(s.substring(1)) + s.charAt(0);   
}

You have to find the first word in the String , pass the rest of the String to the recursive call, and append the first word at the end:您必须找到String中的第一个单词,将String的 rest 传递给递归调用,并将 append 传递给末尾的第一个单词:

public static String reverse(String str) {
    if(str.isEmpty() || !str.contains(" "))
        return str;

    int sep = str.indexOf(' ');
    return reverse(str.substring(sep+1)) + " " + str.substring(0,sep);   
}

Output: Output:

Before recursion: Cat is running
After recursion: running is Cat

BTW, the loop is your original code is pointless.顺便说一句,循环是您的原始代码毫无意义。 You can simply use str directly instead of creating a copy of it.您可以直接使用str而不是创建它的副本。

You can make it even shorter with:您可以使用以下方法使其更短:

public static String reverse(String str) {
    int sep = str.indexOf(' ');
    return sep >= 0 ? reverse(str.substring(sep+1)) + " " + str.substring(0,sep) : str;
}

I think I made it a little less good than @Eran but I already wrote:我认为我做得比@Eran 差一点,但我已经写过:

private static String reverse(String str) {
    if (str.isEmpty() || !str.contains(" "))
        return str;
    StringBuilder sb = new StringBuilder(" ");
    int i = 0;
    while (i < str.length() && str.charAt(i) != ' ') {
        sb.append(str.charAt(i));
        i++;
    }
    return reverse(str.substring(i + 1)) + sb.toString();
}

Here's another option (untested):这是另一个选项(未经测试):

public static String reverse(String str) {
  String words[] = str.split (" ");
  StringBuilder sb = new StringBuilder();
  j = words.length - 1;
  while (j >= 0) {
    sb.append(" " + words[j--]);
  }
  return sb.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM