问题描述
将字符串中的空格替换成“% 2 0”
问题分析
(1)该问题最简单的解决办法是重新申请一个新的字符串数组,遍历原字符串数组。若是非空格就直接拷贝到新数组,若是空格就直接在新数组中加入“2”,“0”,“%”三个字符。最后遍历结束,将新字符串拷贝给就字符串,释放新申请的字符串的内存空间。但该方法的空间复杂度比较高,因此可能在一定的条件下不太适合。
(2)在原字符串数组上进行操作,因为题意已说明字符串数组的空间足够大。
详细分析
(1)字符在数组中的存储形式
(2)先统计字符串中空格的数量,定义i,j下标。
代码实现
void StrReplace2(char*str)
{
int count = 0;//统计空格个数
int len = strlen(str);
for (int i = 0; i <len-1; i++)
{
if (str[i] = ' ')
{
count++;
}
}
int j = strlen(str) + count * 2;//新的字符串总长度
int i = strlen(str);
while (i >= 0 && j != i);//在有空格时存在时j必大于i
{
if (str[i] != ' ')
{
str[j--] = str[i];
}
else
{
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
--i;
}
}
int main()
{
char str[] = "we are happy";
printf("%s\n", str);
StrReplace2(str);
printf("%s\n", str);
return 0;
}