9.1数组与字符串(三)——将字符串中的空格全部替换为“%20”

来源:互联网 发布:南方gps怎么导出数据 编辑:程序博客网 时间:2024/05/10 17:56
/**
 * 功能:将字符串中的空格全部替换为“%20”。假定该字符串尾部有足够的空间存放新增字符,并且
 * 知道字符串的“真实”长度。
 *注意:java数组长度不可变
 */
注意:处理字符串操作问题时,一般从字符串尾部开始编辑,从后往前反向操作(字符串尾部有额外的缓冲,不必担心覆盖原有数据);
方法:
第一次遍历得到空格数量,计算出字符串的新长度。第二次遍历开始反向编辑字符串。若为空格,则将%20复制到下一个位置,否则复制原先的字符。
      publicstaticchar[] replaceSpaces(char[]str){
            intspacesCount=0;
            intnewLength=str.length;
            for(inti=0;i<str.length;i++){
                  if(str[i]==' ')
                        spacesCount++;
            }
            
            newLength+=spacesCount*2;
            char[]newStr=newchar[newLength];
            for(inti=str.length-1;i>=0;i--){
                  if(str[i]==' '){
                        newStr[newLength-1]='0';
                        newStr[newLength-2]='2';
                        newStr[newLength-3]='%';
                        newLength=newLength-3;
                  }else{
                        newStr[newLength-1]=str[i];
                        newLength--;
                  }
            }
            returnnewStr;
      }
}
0 0
原创粉丝点击