/*
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
#include <iostream>
using namespace std;
class Solution{
public:
void replaceSpace(char *str, int length){ // length 是字符数组总长度
/* 查找str中空格个数,构造新的字符串序列 */
int strLen = strlen(str);
cout << strLen << endl;
if (strLen == 0) return;
char *p = str;
int spaceNum = 0;
while(*p!='\0'){
if (*p == ' ') spaceNum ++;
p++;
}
cout << spaceNum << endl;
if (spaceNum == 0) return; // 无空格,返回
int newLen = strLen + 2*spaceNum;
if (newLen > length){ // 原数组长度不足
cout << "# Error: char array over flow!" << endl;
return;
}
str[newLen] = '\0'; // 注意最后一个字符应该是字符串终止字符,否则可能出错
for(int i = strLen -1, j = newLen-1; i>=0; i--){
if (spaceNum == 0) return;
// i for new, j for old, backword
if(str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
spaceNum --;
}else{
str[j--] = str[i];
}
}
}
};
int main(){
char char_array[30] =" hello world";
Solution sol;
sol.replaceSpace(char_array, 30);
cout << char_array<< endl;
system("pause");
return 0;
}
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
#include <iostream>
using namespace std;
// 整体思路,先查找空格数量,然后从后向前依次复制字符
// 这种情况下,实现需要给定空间大小length,替换之后的字符串长度不能超过该length,否则会内存溢出
class Solution{
public:
void replaceSpace(char *str, int length){ // length 是字符数组总长度
/* 查找str中空格个数,构造新的字符串序列 */
int strLen = strlen(str);
cout << strLen << endl;
if (strLen == 0) return;
char *p = str;
int spaceNum = 0;
while(*p!='\0'){
if (*p == ' ') spaceNum ++;
p++;
}
cout << spaceNum << endl;
if (spaceNum == 0) return; // 无空格,返回
int newLen = strLen + 2*spaceNum;
if (newLen > length){ // 原数组长度不足
cout << "# Error: char array over flow!" << endl;
return;
}
str[newLen] = '\0'; // 注意最后一个字符应该是字符串终止字符,否则可能出错
for(int i = strLen -1, j = newLen-1; i>=0; i--){
if (spaceNum == 0) return;
// i for new, j for old, backword
if(str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
spaceNum --;
}else{
str[j--] = str[i];
}
}
}
};
int main(){
char char_array[30] =" hello world";
Solution sol;
sol.replaceSpace(char_array, 30);
cout << char_array<< endl;
system("pause");
return 0;
}