本文實例講述了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(" ")),倒序輸出即可;
實現代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
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)); } } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/lyg468088/article/details/49725871