This article describes the method of Java implementing the reverse order of word order in English sentences. Share it for your reference, as follows:
Question requirements: Given an English sentence with n lines, the sentences after the reverse order words in the sentence are required, such as:
Input: n=3
I love you
How are you
My name is Liming
Output:
you love I
you are How
Liming is name My
According to the method (split(" ")) provided to us by Java language, you can output in reverse order;
Implementation code:
import java.io.UnsupportedEncodingException;import java.util.Scanner;public class Main { public static String reverseWords(String sentence) { StringBuilder sb = new StringBuilder(sentence.length() + 1); String[] words = sentence.split(" "); for (int i = words.length - 1; i >= 0; i--) { sb.append(words[i]).append(' '); } sb.setLength(sb.length() - 1); return sb.toString(); } @SuppressWarnings("resource") public static void main(String[] args) throws UnsupportedEncodingException { Scanner in = new Scanner(System.in); System.out.printf("Please input how many lines you want to enter(test by jb51): "); String[] input = new String[in.nextInt()]; in.nextLine(); for (int i = 0; i < input.length; i++) { input[i] = in.nextLine(); } System.out.printf("/nYour input:/n"); for (String s : input) { System.out.println(reverseWords(s)); } }}Running results:
For more information about Java related content, please check out the topics of this site: "Summary of Java Character and String Operation Skills", "Summary of Java Array Operation Skills", "Summary of Java Mathematical Operation Skills", "Tutorial on Java Data Structure and Algorithm" and "Summary of Java Operation DOM Node Skills"
I hope this article will be helpful to everyone's Java programming.