题目:
请实现一个函数,把字符串中的每个空格替换成“%20”,例如,输入”We are happy.”,则输出”We%20are%20happy.”。
解题思路:
本题主要考察对字符串的处理
一般像这种需要向后扩充容量重新整理内存的,最好能够考虑到从尾部开始整理的方法
1.指针都可以当作数组使用,但是指针本身不检查是否超出数组范围。
2.对字符串的处理都应该考虑最后的空字符’\0’。
3.应该一个一个的处理字符串中的字符,不要向一蹴而就。
4.扩充字符串可以考虑从尾部开始。
5.应该警惕内存覆盖,如果改变字符串会导致字符串变长,那应该考虑内存的问题
Solution:
#include <iostream>
using namespace std;
class Solution{
public:
void replaceSpace(char *str, int length){
if (str == NULL || length <= 0)
return;
int originalLength = 0;
int spaceLength = 0;
for (int i = 0; str[i] != '\0' ; i++) {
if ( str[i] == ' ')
spaceLength++;
originalLength++;
}
int end = spaceLength*2 + originalLength;
if (end + 1 > length)
return;
str[end--] = '\0';
for (int j = originalLength-1; j >= 0 ; j--) {
if ( str[j] != ' '){
str[end--] = str[j];
} else{
str[end--] = '0';
str[end--] = '2';
str[end--] = '%';
}
}
}
};
int main(){
string s;
char* str = new char[100];
// cin不接受空格,将空格切成若干段
getline(cin, s);
str = const_cast<char*>(s.data());// 将string类型转换成char*类型保存
Solution().replaceSpace(str, 100);
cout<< str;
return 0;
}