日期:2014-05-20  浏览次数:20809 次

This is a cup of tea的字符串翻转问题......
将 This is a cup of tea 转为
tea of cup a is This
写完代码发现最后那个This没有转过来还是 sihT
public class TheSwap {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String str="This is a cup of tea";
        char[] chr=str.toCharArray();
        for(char ele:chr){
            System.out.print(ele);
        }
        int l=chr.length;
        for(int i=0;i<l/2;i++){
            char temp=chr[i];
            chr[i]=chr[l-i-1];
            chr[l-i-1]=temp;
        }
        System.out.println();
        for(char ele:chr){
            System.out.print(ele);
        }
        System.out.println();
        swapIn(chr);
        System.out.println("FINAL IS:");
        for(char ele:chr){
            System.out.print(ele);
        }
    }
    
    private static void swapIn(char[] c){
        int count=0;
        for(int i=0;i<c.length;i++){ 
            if(c[i]!=' '){
                count++;
                continue;
        }
            if(c[i]==' ' || (i==c.length-1)){
                if(count==1){
                    count=0;
                    continue;
                }
                else{
                    int tempCount=0;
                    for(int j=i-count;j<i-Math.floor(count/2);j++){
                        char ctemp=c[j];
                        c[j]=c[i-1-tempCount];
                        c[i-1-tempCount]=ctemp;
                        tempCount++;
                    }
                    count=0;
                }
            }
        }
        
    }
}
java 字符反转

------解决方案--------------------
LZ的代码看的头大,来个简单点的~

public class TheSwap {
public static void main(String[] args) {