反转java中的句子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18782566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:01:23  来源:igfitidea点击:

Reversing the Sentence in java

java

提问by Som

I m inserting a string in my program

我在我的程序中插入一个字符串

String str = " I live in India"; 

how can in get reversed string of that like

怎么能得到这样的反转字符串

String str ="India in live I"

this is an interview question in my interview. Please any one can help me out in this question

这是我面试中的一个面试题。请任何人都可以帮助我解决这个问题

采纳答案by Konstantin Yovkov

Split it and then add it to a new Stringin reverse order.

拆分它,然后String以相反的顺序将其添加到新的。

String s = " I live in India";
String[] split = s.split(" ");
String result = "";
for (int i = split.length - 1; i >= 0; i--) {
  result += (split[i] + " ");
}
System.out.println(result.trim());

This prints:

这打印:

India in live I

回答by LuigiEdlCarno

String str = "I live in India";
String result = "";
String[] words = str.split(" ");
for (int i=words.length-1;i>=0;i--){
    result = result + words[i] + " ";
}
result = result.subString(result, 0, result.length-1); // remove the last " "

This code splits the String along the whitespaces, so that you get an array of the words. Then a for loop iterates through the array from last to first element and appends the words plus a whitespace to the result string. Finally the whitepace after the last word is removed.

此代码沿空格拆分字符串,以便您获得单词数组。然后 for 循环从最后一个元素到第一个元素遍历数组,并将单词和空格附加到结果字符串。最后删除最后一个单词后的空白。

回答by SpringLearner

try this way

试试这个方法

public class test {
    public static void main(String args[])
    {

        String x="i live in india";
        String y[]=x.split(" ");
        System.out.println(y[3]+" "+y[2]+" "+y[1]+" "+y[0]);
// if the input string is different meaning if the number of words are greater than or less than four then try this way

/*for(int i=y.length-1;i>=0;i--)
        {
            System.out.print(y[i]+ " ");
        }*/
    }

}

this is the screenshot to show the output enter image description here

这是显示输出的屏幕截图 在此处输入图片说明