本文实例讲述了Java实现英文句子中的单词顺序逆序输出的方法。分享给大家供大家参考,具体如下:
“只有客户发展了,才有我们的生存与发展!”这是成都创新互联公司的服务宗旨!把网站当作互联网产品,产品思维更注重全局思维、需求分析和迭代思维,在网站建设中就是为了建设一个不仅审美在线,而且实用性极高的网站。创新互联对网站建设、成都网站设计、网站制作、网站开发、网页设计、网站优化、网络推广、探索永无止境。题目要求:给定n行的英文句子,要求输出句子中逆序单词后的句子,如:
输入:n=3
I love you
How are you
My name is Liming
输出:
you love I
you are How
Liming is name My
依据Java语言给我们提供的拆分空格间隔的单词的方法(split(" ")),倒序输出即可;
实现代码:
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)); } } }