首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

This is a cup of tea的字符串翻转有关问题.

2013-11-03 
This is a cup of tea的字符串翻转问题......将 This is a cup of tea 转为tea of cup a is This写完代码

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) {


String str = "This is a cup of tea";
char[] arr = str.toCharArray();
System.out.println("before:" + str);
swapIn(arr);
System.out.println("after:" + String.valueOf(arr));
}

private static void swapIn(char[] arr) {
if(arr.length == 0) return;//空串
//反转整个字符串
rotate(arr, 0, arr.length - 1);
//以空格区分,逐个反转子字符串
int count = 0;//非空格字符数量
for(int i = 0;i < arr.length;++i) {
if(arr[i] != ' ') ++count;
else {
rotate(arr, i - count, i - 1);
count = 0;
}
}
//反转最后一个字符串
rotate(arr, arr.length - count, arr.length - 1);
}

//反转字符串
private static void rotate(char[] arr,int start,int end) {
for(int i = start;i <= (start + end) / 2;++i) {
char temp = arr[i];
arr[i]= arr[end - (i - start)];
arr[end - (i - start)] = temp;
}
}
}


This is a cup of tea的字符串翻转有关问题.

热点排行