Java 翻转字符串中的单词

Input: Annuity Lump sum from Annuity Target fund_20170918!
Output1: ytiunnA pmuL mus morf ytiunnA tegraT !81907102_dnuf,只翻转单词中的字符顺序
Output2:!81907102_dnuf tegraT ytiunnA morf mus pmuL ytiunnA, 直接全部翻转

/**
 * 
 * @author Administrator
 * date 06.May.2018
 */
public class RevDemo {
    
        public static void swapStr(char[] arr, int begin, int end){
            while (begin < end){
                char tmp = arr[begin];
                arr[begin] = arr[end];
                arr[end] = tmp;
                begin++;
                end --;
            }
        }

        public static void revStr(String s){
            //initialize ret
            String ret = " ";
            
            //如果结尾没有空格,需要补上,否则最后一个单词不会反转
            if(!s.endsWith(" ")){
                s += " ";
            }

            char[] charArr = s.toCharArray();
            
            int begin = 0;
            for(int i = 0;i <= s.length()-1; i++){
                if (charArr[i] == ' '){
                    swapStr(charArr,begin,i-1);
                    begin = i+1;
                }
            }
            
            ret = new String(charArr);
            System.out.println(ret);;
        }
    
        public static void revAll(String s){
            for(int i = s.length()-1; i >=0; i--){
                char c = s.charAt(i);
                System.out.print(c);
            }
            //换行
            System.out.println();
        }
        
        public static void main (String[] args){
            
            String str = "Annuity Lump sum from Annuity Target fund_20170918!";
            System.out.println(str);
            revStr(str);
            revAll(str);
        }
}


//Annuity Lump sum from Annuity Target fund_20170918!
//ytiunnA pmuL mus morf ytiunnA tegraT !81907102_dnuf 
//!81907102_dnuf tegraT ytiunnA morf mus pmuL ytiunnA

你可能感兴趣的:(Java 翻转字符串中的单词)