程序反转字符串中的单词 [英] Program to reverse the words in a string

查看:44
本文介绍了程序反转字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序来反转字符串中的单词.如果 i/p 是狗在追"那么o/p应该是追是狗"

I have written a program to reverse the words in a string. if i/p is "The dog is chasing" then o/p should be "chasing is dog The"

public class String_reverse {

    public static void main(String[] args) {

        String input= "The dog is chasing";

        String[] arr= input.split(" ");
        String reverse="";
        for(int i=arr.length-1;i>=0;i--)
        {
            reverse+= ((reverse.equals(""))?"":" ")+arr[i];
        }
        System.out.println(reverse);

    }

}

但是我不知道如何使用递归来编写这个程序.当我尝试在 stackoverflow 中搜索时,我可以找到反转字符串;但不能颠倒字符串中的单词.

But I don't know how to write this program using recursion. When I tried searching in stackoverflow, I could find reversing a string; but not reversing the words in a string.

推荐答案

递归方法开始时似乎有点困难,但请尝试执行以下操作:

Recursive methods could seem a bit hard when beginning but try to do the following :

  • 尽可能简化问题,找到自己要解决的不太复杂的案例.(例如,您可以使用包含两个词的句子).

  • Simplify the problem as much as possible to find yourself with the less complicated case to solve. (Here for example, you could use a sentence with two words).

先在纸上做,用伪代码帮你处理用最简单的语言解决问题.

Begin with doing it on a paper, use Pseudocode to help you dealing with the problem with the simplest language possible.

开始编写代码,不要忘记对递归进行转义.

Begin to code and do not forget an escape to your recursion.

public static void main(String[] args) {
    String s = reverseSentence("This sentence will be reversed - I swear".split(" "));
    System.out.println(s);
}

public static String reverseSentence(String[] sentence){
    if (sentence.length <= 1){
        return sentence[0];
    }
    String[] newArray = new String[sentence.length-1];
    for (int i = 0 ; i < newArray.length ; i++){
        newArray[i] = sentence[i];
    }
    return sentence[sentence.length-1] + " " + reverseSentence(newArray);
}

这篇关于程序反转字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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