【剑指offer】替换空格

来源:互联网 发布:新湖财富知乎 编辑:程序博客网 时间:2024/06/08 04:36

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。


public class TestReplaceSpace {    public static void main(String[] args) {        StringBuffer str = new StringBuffer("We Are Happy");        System.out.print(replaceSpace2(str));    }    public static String replaceSpace(StringBuffer str) {        if (str == null) {            return null;        }        StringBuilder sb = new StringBuilder();// 新字符串        for (int i = 0; i < str.length(); i++) {            if (str.charAt(i) == ' ') {                sb.append("%20");            } else {                sb.append(str.charAt(i));            }        }        return sb.toString();    }    public static String replaceSpace2(StringBuffer str) {        if (str == null) {            return null;        }        int spaceNum = 0; // 原字符串空格个数        for (int i = 0; i < str.length(); i++) {            if (str.charAt(i) == ' ') {                spaceNum++;            }        }        int newLength = spaceNum * 2 + str.length(); // 新长度 = 原字符串空格个数*2 + 原长        int oldEnd = str.length() - 1; // 原字符串尾指针        int newEnd = newLength - 1; // 新字符串尾指针        str.setLength(newLength); // 扩充原字符串长度为新长度        while (oldEnd >= 0) {            if (str.charAt(oldEnd) == ' ') {                str.setCharAt(newEnd--, '0');                str.setCharAt(newEnd--, '2');                str.setCharAt(newEnd--, '%');                oldEnd--;                continue;            } else {                str.setCharAt(newEnd--, str.charAt(oldEnd--));            }        }        return str.toString();    }}

replaceSpace() 方法新建了一个 StringBuilder 对象来复制原字符串的内容并将里面的空格替换成”%20”;

replaceSpace2() 方法则先计算原字符串里的空格,扩充原字符串长度,从后往前复制原字符串里的值,并替换空格。


StringBuffer 的 setLength 函数用法如下:

void java.lang.StringBuffer.setLength(int newLength)

Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character ‘\u005Cu0000’. In other words, if the newLength argument is less than the current length, the length is changed to the specified length.
If the newLength argument is greater than or equal to the current length, sufficient null characters (‘\u005Cu0000’) are appended so that length becomes the newLength argument.
The newLength argument must be greater than or equal to 0.

该函数没有返回值。
若参数 newLength 大于或等于原长度,原来字符串里的字符位置不变,新多出来的位置用 null 字符(‘\u005Cu0000’)填充;
若参数 newLength 小于原长度,就相当于在原字符串上截取 newLength 长度的字符串。
newLength >= 0

1 0
原创粉丝点击