{面试题4: 替换空格}

From 剑指Offer 何海涛 著

#include <iostream>
#include <cstring>

void replaceBlank(char *str, int length) {
    if(str != NULL && length > 0) {
        int numberOfBlank = 0;
        int originLength = 0;
        while(str[originLength] != '\0') {
            if(str[originLength++] == ' ') {
                numberOfBlank++;
            }
        }
        int newLength = originLength + (numberOfBlank<<1);
        if(newLength <= length) {
            int indexOfOrigin = originLength;
            int indexOfNew = newLength;
            while(indexOfOrigin < indexOfNew) {
                if(str[indexOfOrigin] == ' ') {
                    str[indexOfNew--] = '0';
                    str[indexOfNew--] = '2';
                    str[indexOfNew--] = '%';
                } else {
                    str[indexOfNew--] = str[indexOfOrigin];
                }
                indexOfOrigin--;
            }
        }
    }
}

测试集:

void test(char *str, int length, char *expected) {
    std::cout << std::boolalpha << (replaceBlank(str, length), str != NULL && expected != NULL && strcmp(str, expected) == 0 ? true : str == expected) << std::endl;
}

int main(int argc, char* argv[]) {

    char str1[32] = "";
    char str2[32] = "   ";
    char str3[32] = "Hello World!";
    char str4[32] = " HelloWorld!";
    char str5[32] = "HelloWorld! ";
    char str6[32] = "Hello  World!";

    test(NULL, 0, NULL);
    test(str1, 16, "");
    test(str2, 32, "%20%20%20");

    test(str3, 32, "Hello%20World!");
    test(str4, 32, "%20HelloWorld!");
    test(str5, 32, "HelloWorld!%20");

    test(str6, 32, "Hello%20%20World!");

    retur 0;

}

 

posted @ 2015-04-19 14:23  long#long  阅读(119)  评论(0编辑  收藏  举报