您的位置:首页 > Web前端

剑指Offer-4-替换空格

2015-09-26 15:36 369 查看
题目:请实现一个函数,把字符串中的每个空格替换成“%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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 剑指Offer