Analysis:
Replace the space in the string with three characters '% ', ' 2 ', ' 0 ';
One, create another array is too simple, the contents of the string str copied into the new array, when encountered "will output% 20; If there is no space, the original string of characters copied over it is good;
Second, calculate the number of spaces in the string, and then calculate the length of the replacement string, because instead of the original string will overwrite the characters, so we should traverse when we encounter a space to move the character behind it two bits, so that the%20 can be put in, but because each time you encounter a space to move backwards, Then there is no efficiency, so we can move the last character to the last one at a time.
The steps are this:
Figure out that the string has 13 characters (' s '), plus the space to replace the spaces, altogether 13+2*2=17, then we can assign the original length to oldlen=13, the new length assigned to newlen=17;
First, the last character of the string is moved to the last space, that is, ' \ n ' moved to the position of the Newlen;
Then move the ' Y ' to the second-to-last position, move it, and when it encounters the ' 0 ' place where the space should be moved, and then put ' 2 '% ' in turn, then continue to move a character in front of the space to the position in front of '% ', moving until the end of the move;
The code is as follows:
#include <stdio.h>
#include <assert.h>
#include <string.h>
void Replace_black (char *str)
{
Char *pstr=str;
int Oldlen=strlen (str);
int newlen=0;
int count=0;
while (*PSTR)
{
if (*pstr== ")
Count + +;
pstr++;
}
Newlen=oldlen+2*count;
while (Oldlen < Newlen)
{
if (str[oldlen]== ")
{
str[newlen--] = ' 0 ';
str[newlen--] = ' 2 ';
str[newlen--] = '% ';
oldlen--;
}
Else
str[newlen--]=str[oldlen--];
}
}
int main ()
{
Char str[20]= "We are happy";
Replace_black (str);
printf ("%s", str);
return 0;
}
37,1 Bot
Change the space in the string to%20 such as "We are happy" into "we%20are%20happy"