问题描述
将 “we are happy”中的空格替换为“%20”。
即输入“we are happy”
输出“we%20are%20happy”
代码一
//如果直接遍历碰到空格,后面所有的往后移动,则徒劳的移动太多,
//目标:所有的字符串一次移动到位,移动最少
//1.统计空格的数量
//2.确定直接就在原来的字符串上移动,节省空间
//3.确定从前往后遍历(需要新开字符串),还是从后往前遍历(不用新开,从后往前没一个字符串都是一次移动到位)
void Replace(char *str, int len)
{
assert(str != NULL);
int count = 0;
char *p = str;
int lenChar = 0;
//统计空格数目
while (*p != '\0')
{
if (*p == ' ')
{
count++;
}
lenChar++;
p++;
}
int newlen = count * 2 + lenChar;
if (newlen > len)
{
return;
}
int i = lenChar;
int j = newlen;
while (i >= 0 && j >=0)
{
if (str[i] == ' ')
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
else
{
str[j--] = str[i];
}
i--;
}
}
int main()
{
char str[100] = " a sl awql dwle awq ";
Replace(str, 100);
printf("%s\n", str);
getchar();
return 0;
}
代码二:利用近容器string及其相关函数
void Replace(string &str)
{
/*
遍历str
若为空格 erase空格 分别insert % 2 0;
注意!!! 迭代器失效问题 每次 erase或insert都要用it保存返回值
由于是在当前位置插入 因此要 0 2 % 这样插入 然后it要向后偏移3个,跳过%20 进行遍历
*/
auto it = str.begin();
while (it != str.end())
{
if (*it == ' ')
{
it = str.erase(it);
it = str.insert(it, '0');
it = str.insert(it, '2');
it = str.insert(it, '%');
it += 3;
}
else
{
++it;
}
}
}
int main()
{
string str = "we are happy";
Replace(str);
for (char val : str)
{
cout << val;
}
cout << endl;
getchar();
return 0;
}