Reverse a given sentence in Java

前端 未结 14 1911
别跟我提以往
别跟我提以往 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条回答
  •  Happy的楠姐
    2020-11-27 05:29

    No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:

    String input = "This is interview question";
    
    List list = Arrays.asList(input.split(" "));
    Collections.reverse(list);
    System.out.println(list.stream().collect(Collectors.joining(" ")));
    

提交回复
热议问题