程序設計(可用任何編程語言實現(xiàn))
前后顛倒輸入的英文中的單詞位置,標點符號(只可以出現(xiàn)在句尾)位置不變,如輸入"Hello how are
you!"輸出應該為“you are how Hello!"。
public class fanzhuan { public static void reverse(char[] input,int start,int end){ char temp=0; while(start<end){ temp=input[start]; input[start]=input[end]; input[end]=temp; start++; end--; } } public static void rotateWord(char[] input){ int end=input.length-1; boolean flag=false; if ((input[end]>='a'&&input[end]<='z')||(input[end]>='A'&&input[end]<='Z')){ } else { flag=true; end--; } reverse(input,0,end); int l=-1; int r=-1; for (int i=0;i<=end;i++){ if (input[i]!=' '){ l=i==0||input[i-1]==' '?i:l; r=i==end||input[i+1]==' '?i:r; } if (l!=-1&&r!=-1){ reverse(input,l,r); l=-1; r=-1; } } } public static void main(String[] args) { String test="hello word!"; char[] test1=test.toCharArray(); rotateWord(test1); String test2=String.valueOf(test1); System.out.println(test2); } }
@Test public void test7(){ String a = "Hello how are you!"; StringBuffer sb = new StringBuffer(); char last = a.charAt(a.length()-1); //Unicode 編碼并不只是為某個字符簡單定義了一個編碼,而且還將其進行了歸類。 //這里24表示標點符號這一類型 if(Character.getType(last)==24){ a = a.substring(0, a.length()-1); } String[] splits = a.split("\\s"); for (int i = splits.length-1; i >= 0; i--) { sb.append(splits[i]+(i==0?"":" ")); } sb.append(last); System.out.println(sb.toString()); }