题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,这输出“We%20are%20happy.”
#include <iostream>
using namespace std;
void replace(char* str) {
int BlankCount = 0;
int pos = 0;
while(str[pos] != '\0') {
if(str[pos] == ' ')
BlankCount++;
pos++;
}
int LastPos = pos + 2*BlankCount;
while(BlankCount > 0) {
if(str[pos] != ' ') {
str[LastPos--] = str[pos];
}
else {
BlankCount--;
str[LastPos--] = '0';
str[LastPos--] = '3';
str[LastPos--] = '#';
}
pos--;
}
}
void transver(char* str) {
int i = 0;
while(str[i] != '\0') {
cout<<str[i];
i++;
}
cout<<endl;
}
int main(int argc, char *argv[])
{
char str[100] = "we are happy.";
//char str[100] = " ";
//char str[100] = "w e";
//char str[100] = "we ";
replace(str);
transver(str);
return 0;
}