您的位置:首页 > 其它

【字符串1】-替换空格

2016-07-26 19:06 507 查看
【题目】实现一个函数 将语句中的空格转换成字符“%20”

package com.exe1.offer;
//2 实现一个函数 将语句中的空格转换成字符“%20”
/**
* 思路: 1 得到原字符串长度和加入空格后的长度;
* 2 定义两个指针,分别指向原字符串和加入空格后字符串的最后一格;
* 3 将原字符串复制到新的数组当中;
* 4 只要旧指针和指针没相遇,就逐步操作,具体步骤如下。
* @author WGS
*
*/

public class ReplaceSpace {
//得到字符串中空格数
public int getBlankNum(String str){
int count=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
count++;
}
}
return count;
}
//替换
public String replaceBlank(String string){
String str=string.toString();
//统计空格数
int count=getBlankNum(str);
//获取原来字符串的长度
int originalStrLength=str.toCharArray().length;
//计算替换空格之后需要的长度
int newStrLength=originalStrLength+count*2;
//把原字符串复制到tempArray数组中
char[] tempArray=new char[newStrLength];
System.arraycopy(str.toCharArray(), 0, tempArray, 0, originalStrLength);
//定义两个指针
int originalIndex=originalStrLength-1;
int newIndex=newStrLength-1;

//当originalStrIndex == newStrIndex的时候替换完毕
while(originalIndex>=0 && originalIndex!= newIndex) {
if(tempArray[originalIndex]==' '){//当 旧指针指向的值为空格时(此时新指针指向最开始),将空格的地方改为字符串%20
tempArray[newIndex--]='%';
tempArray[newIndex--]='2';
tempArray[newIndex--]='0';
}else{
tempArray[newIndex--]=tempArray[originalIndex];//当旧指针指向的值不是空格时,就将其值复制到新指针指向的空格,一点一点往前复制,直至遇到空格。
}
originalIndex--;
}

return new String(tempArray);

}
public static void main(String[] args){
String s=new ReplaceSpace().replaceBlank("We are happy");
System.out.println(s);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: