输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
输入“you are so beautiful”,则输出“beautiful so are you”
public static void main(String[] args) { System.out.print("输入操作的字符:"); Scanner input = new Scanner(System.in); String str = input.nextLine(); String[] strtemp = str.split(" "); StringBuffer sb = new StringBuffer();//存放反转后的sb for(String s:strtemp) { StringBuffer sbuf = new StringBuffer(s); sbuf = sbuf.reverse(); sb.append(sbuf.toString()); sb.append(" "); } System.out.println(sb.toString()); }上述输入you are so beautiful,输出uoy era os lufituaeb,单词内部反转,数序不变。
下面实现输出“beautiful so are you”
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.Map.Entry; public class restrings { /** * @param args * you are so beautiful”,则输出“beautiful so are you” */ public static void main(String[] args) { System.out.print("输入操作的字符:"); Scanner input = new Scanner(System.in); String str = input.nextLine(); String[] strs = str.split(" "); StringBuffer sb = new StringBuffer(); Map<Integer,String> map = new HashMap<Integer, String>(); for (int i = 0; i < strs.length; i++) { map.put(i,strs[i]); } for (int i = map.size()-1; i > -1; i--) { String temp = map.get(i); sb.append(temp); sb.append(" "); } System.out.println(sb.toString()); } }
主要用String.reverse()方法和对map的应用。