用递归在Java中反转单词

huangapple go评论63阅读模式
英文:

Reverse the words in Java with recursively

问题

public class PrintElements {

    public static void printReverse(String str) {
        if ((str == null) || (str.length() <= 1))
            System.out.print(str);
        else {
            int lastSpaceIndex = str.lastIndexOf(' ');
            if (lastSpaceIndex != -1) {
                System.out.print(str.substring(lastSpaceIndex + 1) + " ");
                printReverse(str.substring(0, lastSpaceIndex));
            } else {
                System.out.print(str.charAt(str.length() - 1));
                printReverse(str.substring(0, str.length() - 1));
            }
        }
    }

    public static void main(String[] args) {
        String str = "this function reverse";
        printReverse(str);
    }

}

请注意,我已经修复了你的代码,使其能够正确地反转单词的顺序。现在,输入 "this function reverse" 将产生输出 "reverse function this",而不再是 "esrever noitcnuf siht"。

英文:
public class PrintElements {
	
	 public static void printReverse (String str)
	    {
		        if ((str==null)||(str.length() &lt;= 1)) 
		           System.out.print(str); 
		        else
		        { 
		            System.out.print(str.charAt(str.length()-1));             
		        	printReverse(str.substring(0,str.length()-1)); 
		        }    
	    }

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String str=&quot;this function reverse&quot;;
        printReverse(str);
		 
	}

}

In this method, I am trying to just change the place the words not letters place with using recursion.

For example, if &quot;this function reverse&quot; is the input, the output should be &quot;Reverse function this&quot;.

But my current output is : &quot;esrever noitcnuf siht&quot;

答案1

得分: 1

import java.util.Arrays;

public class Main {
    public static void printReverse(String str) {
        if (str == null || !str.contains(" ")) {
            System.out.print(str);
            return;
        }
        String[] words = str.split("\\s+");// Split str on space(s)
        System.out.print(words[words.length - 1] + " ");// Print the last element

        // Call the method recursively by passing a new string with all but last word
        printReverse(String.join(" ", Arrays.asList(words).subList(0, words.length - 1)));

    }

    public static void main(String[] args) {
        String str = "this function reverse";
        printReverse(str);
    }
}

**Output:**

reverse function this
英文:

Do it as follows:

import java.util.Arrays;

public class Main {
	public static void printReverse(String str) {
		if (str == null || !str.contains(&quot; &quot;)) {
			System.out.print(str);
			return;
		}
		String[] words = str.split(&quot;\\s+&quot;);// Split str on space(s)
		System.out.print(words[words.length - 1] + &quot; &quot;);// Print the last element

		// Call the method recursively by passing a new string with all but last word
		printReverse(String.join(&quot; &quot;, Arrays.asList(words).subList(0, words.length - 1)));

	}

	public static void main(String[] args) {
		String str = &quot;this function reverse&quot;;
		printReverse(str);
	}
}

Output:

reverse function this

答案2

得分: 0

public static String reverseString(String str) {
    if (str == null)
        return "";
    if (!str.contains(" "))
        return str;

    int whitespacePos = str.indexOf(" ");
    String firstWord = str.substring(0, whitespacePos);
    return reverseString(str.substring(whitespacePos + 1)) + " " + firstWord;
}

public static void main(String[] args) {
    String str = "this function reverse";
    System.out.println(reverseString(str));
}
英文:
public static String reverseString(String str) {
    if (str == null)
        return &quot;&quot;;
    if (!str.contains(&quot; &quot;))
        return str;

    int whitespacePos = str.indexOf(&quot; &quot;);
    String firstWord = str.substring(0, whitespacePos);
    return reverseString(str.substring(whitespacePos + 1)) + &quot; &quot; + firstWord;
}

public static void main(String[] args) {
    String str = &quot;this function reverse&quot;;
    System.out.println(reverseString(str));
}

I tested this code and it works

  1. It is (most of the time) cleaner to return a String, and then print this String if you want to.

  2. If you use charAt(), you are only getting individual characters. Therefore it will be difficult to not also reverse the letters of the words. It is easier to find the whitespaces between the words and then to retrieve whole words with subString()

  3. the subString() method can take two parameters, startIndex and endIndex, or just one parameter, only the startIndex. It then returns the subString from this startIndex up to the end of the String.

Note: I know you can use split(), I wanted to show how it can be done with indexes. If you already use split(), you might aswell not use recursion.

答案3

得分: 0

尝试这个。它遍历输入字符串,找到每个单词,然后通过颠倒单词的顺序将它们合并到颠倒的字符串中。

public static void printReverse(String str) {
    if ((str == null) || (str.equals(""))) 
        return;
    str = str + " "; // 在末尾添加一个空格,这将有助于检测最后一个单词
    String revStr = "", word = "";
    char c;
    for (int i = 0; i < str.length(); i++) {
        c = str.charAt(i);
        if (c != ' ') {
            word = word + c;
        } else {
            revStr = word + " " + revStr;
            word = "";
        }
    }

    System.out.println(revStr.trim()); // 移除末尾的额外空格
}
英文:

Try this. It traverses the input string and finds out each word and then merges them into the reversed string by reversing the order of the words.

public static void printReverse (String str)
{
    if ((str == null) || (str.equals(&quot;&quot;))) 
       return ;
    str = str + &quot; &quot;; //to add a space at the end. this will help in detecting the last word
    String revStr = &quot;&quot;, word = &quot;&quot;;
    char c;
    for (int i=0; i &lt; str.length(); i++)
    {
         c = str.charAt(0);
         if (c != &#39; &#39;)
         {
             word = word + c;
         }
         else
         {
             revStr = word + &quot; &quot; + revStr;
         }
    }
    
    System.out.println(revStr.Trim()); //removes the extra space from the end
    
    }
}

答案4

得分: 0

public static void reverseWords(String str) {
    if (str == "" || str == null) {
        return;
    } else {
        String[] _str = str.split(" ");
        System.out.println(_str[_str.length - 1]);
        String[] newArr = Arrays.copyOf(_str, _str.length - 1);
        reverseWords(String.join(" ", newArr));
    }
}

不要忘记导入:

import java.util.Arrays;
英文:
public static void reverseWords(String str){
        if(str==&quot;&quot; || str==null){ 
            return;
        }else {
            String[] _str = str.split(&quot; &quot;);
            System.out.println(_str[_str.length-1]);
            String[] newArr = Arrays.copyOf(_str,_str.length-1);
            reverseWords(String.join(&quot; &quot;, newArr));
        }
    }

dont forget to import

import java.util.Arrays;

答案5

得分: 0

public String reverseString(String str){
    if(str.lastIndexOf(32) ==-1){
        return str;
    }
    return str.substring(str.lastIndexOf(32)+1)+" "+reverseString(str.substring(0,str.lastIndexOf(32)));

    //Here lastIndexOf() method get the last element of space so that method substring takes the String after last space because is used lastIndexOf(32)+1 and 
   //reverseString() method continuously takes up to n-1 from nth string until lastIndexOf() return -1 i.e no more whitespace avaliable 

}
英文:
public String reverseString(String str){
    if(str.lastIndexOf(32) ==-1){ //32 is an ASCII value for space 
        return str;
    }
    return str.substring(str.lastIndexOf(32)+1)+&quot; &quot;+reverseString(str.substring(0,str.lastIndexOf(32)));
    
    //Here lastIndexOf() method get the last element of space so that method substring takes the String after last space because is used lastIndexOf(32)+1 and 
   //reverseString() method continuously takes up to n-1 from nth string until lastIndexOf() return -1 i.e no more whitespace avaliable 

}

答案6

得分: 0

这是一个解决方案:

public String reverseString(final String str){
    // 使用三元运算符
    return (str.lastIndexOf(32) == -1)
        ? str
        : str.substring(str.lastIndexOf(32) + 1) + " "  + reverseString(str.substring(0, str.lastIndexOf(32)));
}

或者使用 if-else:

public String reverseString(final String str){
    if (str.lastIndexOf(32) == -1))
        return str;
    else
        return str.substring(str.lastIndexOf(32) + 1) + " "  + reverseString(str.substring(0, str.lastIndexOf(32)));
}

32 是空格字符的 ASCII 码。所以如果字符串中没有空格,它只会返回字符串(单词)。如果有空格,它会递归地交换空格后的部分和空格前的单词。

英文:

Here's a solution:

public String reverseString(final String str){
    //Using ternary operator
    return (str.lastIndexOf(32) == -1)
        ? str
        : str.substring(str.lastIndexOf(32) + 1) + &quot; &quot;  + reverseString(str.substring(0, str.lastIndexOf(32)));
}

or with if-else:

public String reverseString(final String str){
    if (str.lastIndexOf(32) == -1))
        return str;
    else
        return str.substring(str.lastIndexOf(32) + 1) + &quot; &quot;  + reverseString(str.substring(0, str.lastIndexOf(32)));
}

32 is the space character. So if there's no space in the string it just returns the string (word). If there is one it recursively swaps the tail after the and the word before it.

huangapple
  • 本文由 发表于 2020年4月8日 21:19:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61101712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定