剑指Offer 面试题5:替换空格
2020-06-29 04:57
891 查看
面试题5:替换空格
题目:
请实现一个函数,把字符串中的每个空格替换成“%20”。例如,输入“We are happy.”则输出“We%20are%20happy”
- 思路
先计算所有空格数,然后按照所有空格数的数量实现计算出最后一个字符所在位置,再从后往前遍历用两个指针复制字符,如果遇到空格就将代替字符写入,直到两个指针相等。
#include "stdafx.h" #include <string> void ReplaceBlank(char *string, unsigned int length) { if (string == nullptr || length < 1) return; int i = 0; unsigned int blankCount = 0; unsigned int originalLength = 0; while (string[i]!='\0') { originalLength++; if (string[i] == ' ') blankCount++; i++; } unsigned newLength = originalLength + blankCount*2; if (newLength > length) return; int indexOfNew = newLength; int indexOfOriginal = originalLength; while (indexOfOriginal >= 0&&indexOfNew>indexOfOriginal) { if (string[indexOfOriginal]==' ') { indexOfOriginal--; string[indexOfNew--] = '0'; string[indexOfNew--] = '2'; string[indexOfNew--] = '%'; } else string[indexOfNew--] = string[indexOfOriginal--]; } } // ====================测试代码==================== void Test(char* testName, char str[], int length, char expected[]) { if (testName != nullptr) printf("%s begins: ", testName); ReplaceBlank(str, length); if (expected == nullptr && str == nullptr) printf("passed.\n"); else if (expected == nullptr && str != nullptr) printf("failed.\n"); else if (strcmp(str, expected) == 0) printf("passed.\n"); else printf("failed.\n"); } // 空格在句子中间 void Test1() { const int length = 100; char str[length] = "hello world"; Test("Test1", str, length, "hello%20world"); } // 空格在句子开头 void Test2() { const int length = 100; char str[length] = " helloworld"; Test("Test2", str, length, "%20helloworld"); } // 空格在句子末尾 void Test3() { const int length = 100; char str[length] = "helloworld "; Test("Test3", str, length, "helloworld%20"); } // 连续有两个空格 void Test4() { const int length = 100; char str[length] = "hello world"; Test("Test4", str, length, "hello%20%20world"); } // 传入nullptr void Test5() { Test("Test5", nullptr, 0, nullptr); } // 传入内容为空的字符串 void Test6() { const int length = 100; char str[length] = ""; Test("Test6", str, length, ""); } //传入内容为一个空格的字符串 void Test7() { const int length = 100; char str[length] = " "; Test("Test7", str, length, "%20"); } // 传入的字符串没有空格 void Test8() { const int length = 100; char str[length] = "helloworld"; Test("Test8", str, length, "helloworld"); } // 传入的字符串全是空格 void Test9() { const int length = 100; char str[length] = " "; Test("Test9", str, length, "%20%20%20"); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); return 0; }
相关文章推荐
- 《剑指offer》面试题4 替换空格为%20
- 剑指offer 面试题4—替换字符串中空格
- 《剑指offer》面试题4(替换空格)
- 剑指offer:面试题5—替换空格
- 剑指offer面试题:替换空格
- 剑指offer面试题4:替换空格
- 《剑指Offer》面试题4:替换空格
- 剑指Offer(第二版)面试题5:替换空格
- 替换空格(剑指offer面试题4)
- 剑指offer面试题5:替换空格(Java 实现)
- 剑指Offer面试题 - 替换空格
- 《剑指offer》面试题05:替换空格
- 剑指Offer:面试题4 替换空格
- 剑指Offer面试题4[替换空格]
- 剑指offer 面试题4:替换空格
- 面试题04_替换空格_剑指Offer系列
- 剑指offer 面试题4 替换空格
- 《剑指offer》【面试题4:替换空格】
- 剑指Offer 面试题4 替换空格
- 剑指Offer,面试题4,替换空格,Java写法