- 主页/
- [名企面试知识点][Java]字符串中空格替换
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
输入描述
str 是StringBuffer的对象
输出描述
返回替换后的字符串的String对象
题目分析
首先要对输入参数进行判空和越界判断(任何算法题都要注意)。
解法一 (运行时间:36ms 占用内存:688k)
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str==null){
return null;
}
StringBuffer sb = new StringBuffer();
char [] strChar = str.toString().toCharArray();
for(int i=0;i<strChar.length;i++){
if(strChar[i]==' '){
sb.append("%20");
}else{
sb.append(strChar[i]);
}
}
return sb.toString();
}
}
把传入的StringBuffer 对象 str 转换成字符串 再转换成字符数组,申请一个新的StringBuffer 对象 sb来存最后的结果,遍历整个字符数组,如果当前字符为空格则把 "%20"加入到sb中,否则直接追加当前字符,最后把sb转换成字符串返回。
解法二 (运行时间:34ms 占用内存:503k)
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str == null){
return null;
}
for(int i =0;i<str.length();i++){
char c = str.charAt(i);
if(c==' '){
str.replace(i,i+1,"%20");
}
}
return str.toString();
}
}
public StringBuffer replace(int start, int end, String str)
使用给定 String 中的字符替换此序列的子字符串中的字符。该子字符串从指定的 start 处开始,一直到索引 end - 1 处的字符,如果不存在这种字符,则一直到序列尾部。先将子字符串中的字符移除,然后将指定的 String 插入 start。(如果需要,序列将延长以适应指定的字符串。) 参数: start - 起始索引(包含)。 end - 结束索引(不包含)。 str - 将替换原有内容的字符串。 返回: 此对象。
源码(可以看出它调用的是父类的方法)
public synchronized StringBuffer More ...replace(int start, int end, String str) {
453 toStringCache = null;
454 super.replace(start, end, str);
455 return this;
456 }
父类AbstractStringBuilder
822 public AbstractStringBuilder More ...replace(int start, int end, String str) {
823 if (start < 0)
824 throw new StringIndexOutOfBoundsException(start);
825 if (start > count)
826 throw new StringIndexOutOfBoundsException("start > length()");
827 if (start > end)
828 throw new StringIndexOutOfBoundsException("start > end");
829
830 if (end > count)
831 end = count;
832 int len = str.length();
833 int newCount = count + len - (end - start);
834 ensureCapacityInternal(newCount);
835
836 System.arraycopy(value, end, value, start + len, count - end);
837 str.getChars(value, start);
838 count = newCount;
839 return this;
840 }
可以看出StringBuffer类 提供了 插入的函数,值得注意的是 StringBuilder 也是继承于AbstractStringBuilder这个抽象类的。所以它也有这个方法,但是String并没有。
解法三(不推荐,运行时间:38ms 占用内存:654k)
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replaceAll("\\s", "%20");
}
}