【剑指offer系列】-05替换字符串中的空格为%20(关键字:索引从后遍历)

题目:

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

思路:

1.先找出字符串中有多少个空格
2.创建一个大小为str.length+2*空格个数的新数组。因为".“占一位,”%20"占三位,将空格替换成%20,实则没替换一次,多出两位。
3.从字符数组的末尾开始遍历,遇到".“就相应的将”%20"写入新数组相应的位置(新数组也是从末尾开始写入);不是空格的则正常写入即可

public class Main5
{
    private static void replaceEmp(String str)
    {
        if (str == null || str.length() == 0)return;
        //1.计算出新数组的大小
        int count = 0;
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++)
        {
            if (" ".equals(String.valueOf(ch[i])))count++;
        }
        char[] res = new char[ch.length + 2 * count];
        //2.定义两个索引,指向两个数组的末尾
        int chIndex = ch.length - 1;
        int resIndex = res.length - 1;
        for (int i = chIndex; i >= 0; i--)
        {
            if (" ".equals(String.valueOf(ch[i])))
            {
                res[resIndex--] = '0';
                res[resIndex--] = '2';
                res[resIndex--] = '%';
            }else
            {
                res[resIndex --] = ch[i];
            }
        }
        System.out.println(Arrays.toString(res));
    }

    public static void main(String[] args)
    {
        replaceEmp("We are happy.");
    }
}
补充:

" abc".equals(str.charAt(i))书写优于(str.charAt(i)) .equals" abc";因为前者可以有效防止空指针异常
类型转换时即转换为字符串类型时: 3+""的效率低于String.valueOf(3);

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/107772091