剑指offer第四题:字符串中替换空格
1 //============================================================================ 2 // Name : JZ-C-04.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description : Hello World in C++, Ansi-style 7 //============================================================================ 8 9 #include <iostream> 10 #include <string.h> 11 #include <string> 12 using namespace std; 13 14 char* ReplaceBlank(char string[]) { 15 int length = strlen(string); 16 if (length > 0) { 17 int number = 0; //初始化 18 for (int i = 0; i < length; i++) { 19 if (string[i] == ' ') { 20 number++; //先记录空格数 21 } 22 } 23 int newLength = length + number * 2; //重新定义字符串长度 24 char* result = new char[newLength]; //定义新的字符串 25 char *p, *q; //定义两个指向两字符串的指针 26 p = string; 27 q = result; 28 int pIndex = length - 1; //从字符串末尾向前依次输出,遇到空格,转换为%20 29 int qIndex = newLength - 1; 30 while (pIndex >= 0 && qIndex >= 0) { 31 if (p[pIndex] == ' ') { 32 q[qIndex--] = '0'; 33 q[qIndex--] = '2'; 34 q[qIndex--] = '%'; 35 pIndex--; 36 } else { 37 q[qIndex--] = p[pIndex--]; 38 } 39 } 40 q[newLength] = '