08:字符串替换空格
题目:替换空格
实现一个函数,存在字符串hello world!!!,将字符串内的空格字符替换为’%20’。
先对空格个数进行计数,得到适当大小的字符数组,接着将原本数组从后向前替换到新数组中。
public class Offer08 {
public static void main(String[] args) {
String string = "hello world! !";
System.out.println(replaceBlank(string));
}
public static String replaceBlank(String str){
if(str==null||str.length()==0)return null;
char[] chars = str.toCharArray();
//空格计数
int count=0;
for (char c : chars) {
if(c==' ')count++;
}
//新数组大小
int ti = count*2+chars.length;
char[] temp = new char[ti];
//下标
ti--;
//替换
for (int i=chars.length-1;i>=0;i--){
if(chars[i]==' '){
temp[ti--] = '0';
temp[ti--] = '2';
temp[ti--] = '%';
}else{
temp[ti--] = chars[i];
}
}
return new String(temp);
}
}
还没有评论,来说两句吧...