一、问题描述
把空格替换成字符串
例如:we are happy;
替换成:we20%are20%dhappy.
这是剑指offer上的解法,比我想的用另一块空间去拷贝的想法更好。
代码如下:
#include<iostream>
#include<vector>
using namespace std;
void str_copy(char *str)
{
int size = 0;
char *l = str;
while (*str!='\0')
{
if (*str == ' ')
{
size++;
}
++str;
}
int lsize = strlen(l) + 2 * size;
char *p = l + lsize;
char *q = str;
while (p != q&& q!=l)
{
if (*q != ' ')
{
*p = *q;
p--; q--;
}
else
{
*(p--) = '%';
*(p--) = '0';
*(p--) = '2';
q--;
}
}
}
int main()
{
//We are happy.
//we%20are%20happy.
char str[20] = "We are happy";
cout << strlen(str) << endl;
str_copy(str);
cout << str << endl;
}