Reverse a given sentence in Java

前端 未结 14 1825
别跟我提以往
别跟我提以往 2020-11-27 04:52

Can anyone tell me how to write a Java program to reverse a given sentence?

For example, if the input is:

\"This is an interview question\"

相关标签:
14条回答
  • 2020-11-27 05:34

    Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.

    String input = "This is interview question";
    String output = "";
    String[] array = input.split(" ");
    for(int i = array.length-1; i >= 0; i--)
    {
        output += array[i];
        if (i != 0) { output += " "; }
    }
    
    0 讨论(0)
  • 2020-11-27 05:34

    please try below solution, this is working for me.

    public class reverseline {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
            String str="This is interview question";
        String words[]=str.split(" ");
        for(int i=words.length-1;i>=0;i--){
            System.out.print(words[i]+" ");
        }
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题