思路:由于字母之间的字符不唯一,无法使用split进行分割。从后往前进行逐一判断。
1.若当前字符是字母,进行while循环把字母全部粘贴进StringBuilder中。
1).当退出while循环,将sb翻转输出。
2.若不是字母,直接下标-1。继续往前面移动。
public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String str=in.nextLine(); int i=str.length()-1; while(i>=0){ //若是字母 if((str.charAt(i)>='A' && str.charAt(i)<='Z')||(str.charAt(i)>='a' && str.charAt(i)<='z')){ StringBuilder sb=new StringBuilder(); while(i>=0 && ((str.charAt(i)>='A' && str.charAt(i)<='Z')||(str.charAt(i)>='a' && str.charAt(i)<='z'))){ sb.append(str.charAt(i)); i--;//向前移动 } System.out.print(sb.reverse().append(" "));//字符串翻转输出 }else{//不是字母 i--; } } } }