替换空格

2018/02/21 Offer 共 699 字,约 2 分钟

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

替换空格

//cpp:
class Solution {
public:
	void replaceSpace(char *str,int length) {
		int len = length;
		char s1[4] = "%20";
		for (int i = len - 1; i>=0; i--) {
			if (str[i]==' ') {
				for (int j = len + 2; j>i ; j--) {
					str[j] = str[j - 2];
				}
				for (int k = 0; k <= 2; k++) {
					str[i + k] = s1[k];
				}
			}
		}
	}
};
public String replaceSpace(StringBuffer str) {
    int oldLen = str.length();
    for (int i = 0; i < oldLen; i++)
        if (str.charAt(i) == ' ')
            str.append("  ");

    int P1 = oldLen - 1, P2 = str.length() - 1;
    while (P1 >= 0 && P2 > P1) {
        char c = str.charAt(P1--);
        if (c == ' ') {
            str.setCharAt(P2--, '0');
            str.setCharAt(P2--, '2');
            str.setCharAt(P2--, '%');
        } else {
            str.setCharAt(P2--, c);
        }
    }
    return str.toString();
}

Search

    Table of Contents