Cracking the coding interview--Q1.4

原文

Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional
characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation
in place.)
EXAMPLE
Input: "Mr John Smith        "
Output: "Mr%20Dohn%20Smith"

译文:

写一个函数,把字符串中所有的空格替换为%20 ,并且原字符串末尾的空格要忽略。

解答

直接用了java.lang.String里的replaceAll方法,但是为了忽略末尾的空格,先做一些处理,将末尾的空格先修改成一个不可见的其他字符,ASCII小于20的都行。然后替换之后就用trim方法就能去除掉最后的不可见字符。

public class Main {

    public static String replaceSpaces (String str) {
        int len = str.length();
        char a[] = str.toCharArray();
        for(int i = len - 1; i >= 0; i--) {
            if(a[i] == ' '){
                a[i] = 0;
            }
            else
                break;
        }
        String str2 = new String(a);
        return str2.replaceAll(" ", "%20").trim();
    }
        
    public static void main(String args[]) {
        String s1 = "Mr John Smith    ";
        System.out.println(replaceSpaces(s1));
    }
}

但是如果原字符串首包含ASCII小于20的不可见字符的话就有BUG了。所以又改进了一个版本:

public class Main {

    public static String replaceSpaces (String str) {
        int len = str.length();
        boolean flag = true;
        StringBuilder sb = new StringBuilder();
        for(int i = len - 1; i >= 0; i--) {
            if(str.charAt(i) == ' ' && flag){
                continue;
            }
            else if(str.charAt(i) == ' ' && !flag) {
                sb.insert(0, "%20");
            }
            else {
                sb.insert(0, str.charAt(i));
                flag = false;
            }
        }
        return sb.toString();
    }
        
    public static void main(String args[]) {
        String s1 = "Mr John Smith    ";
        System.out.println(replaceSpaces(s1));
    }
}
原文地址:https://www.cnblogs.com/giraffe/p/3186164.html