42翻轉單詞

輸入一個英文句子,翻轉單詞順序,但單詞內字符順序不變,比如輸入i am a student.  輸出student. a am i

分兩步,先翻轉句子中所有字符,再以空格切割,對於每一個字符串再一次翻轉。

public class fourty_two {
 public static void main(String args[]){
	 Scanner cin=new Scanner(System.in);
	 String s=cin.nextLine();
	 StringBuilder b=new StringBuilder(s);
	 s=b.reverse().toString();
	 String temp[]=s.split(" ");
	 for (int i=0;i<temp.length;i++){
		 b=new StringBuilder(temp[i]);
		 temp[i]=b.reverse().toString();
	 }
	 StringBuilder sb=new StringBuilder();
	 for (int i=0;i<temp.length-1;i++){
		 sb.append(temp[i]+" ");
	 }
	 sb.append(temp[temp.length-1]);//最後一個不用空格
	 System.out.println(sb.toString());
 }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章