删除字符串中的多余空格

//For example:       I’m  very happy   to  introduce m    yself  -->          to you  here
// To  I’m very happy to introduce m yself --> to you here        


//Codes:
  String str = "      I’m  very happy   to  introduce m    yself  -->          to you  here       ";
    char[] charArray = str.toCharArray();
    int index = 0;
    int movePoint = 0;
    for(; index<charArray.length; index++){
        if(charArray[index] == ' '){
            while(movePoint<charArray.length && charArray[movePoint] == ' '){
                movePoint++;
            }
            while(movePoint<charArray.length && charArray[movePoint] != ' '){
                index++;
                charArray[index] = charArray[movePoint];
                movePoint++;
            }   
            if(movePoint >=charArray.length ){
                break;
            }
        } else{
            if(index != 0){
                charArray[index] = ' ';
                index = index-1;
            }
        }
    }
    String result = String.valueOf(charArray, 0, index+1);
    System.out.println(result);

 


 

posted on 2014-07-15 07:51  -赶鸭子上架-  阅读(299)  评论(0编辑  收藏  举报