英文:
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() <= 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="this function reverse";
printReverse(str);
}
}
In this method, I am trying to just change the place the words not letters place with using recursion.
For example, if "this function reverse"
is the input, the output should be "Reverse function this"
.
But my current output is : "esrever noitcnuf siht"
答案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(" ")) {
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
答案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 "";
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));
}
I tested this code and it works
-
It is (most of the time) cleaner to return a String, and then print this String if you want to.
-
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()
-
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("")))
return ;
str = str + " "; //to add a space at the end. this will help in detecting the last word
String revStr = "", word = "";
char c;
for (int i=0; i < str.length(); i++)
{
c = str.charAt(0);
if (c != ' ')
{
word = word + c;
}
else
{
revStr = word + " " + 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=="" || 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));
}
}
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)+" "+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) + " " + 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) + " " + 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论