for (i = 0; i < length; i++) { if (str[i] == ' ') { spaceCount++;
Since we replace one character ('') with three characters, we first count the number of spaces to calculate the size increase.
newLength = length + spaceCount * 2; //need space for 2 more characters.. str[newLength] = '\0';
This cannot be done as follows: you must allocate more memory , but here we extend the size of the string variable. I believe that it is best to highlight a new variable, as the next step will be easier with another.
for (i = length - 1; i >= 0; i--) { if(str[i] == ' ') { str[newLength - 1] = '0'; //??? str[newLength - 2] = '2'; str[newLength - 3] = '%'; newLength = newLength - 3; } else { str[newLength - 1] = str[i]; newLength = newLength - 1; } }
Finally, this step should work if the line is correctly expanded, but you can rewrite it a bit to be clearer.
I suggest something similar, assuming that newstr is our new variable, highlighted in the previous step:
int j = 0; for(i = 0; i < length; i++, j++) { if(str[i] == ' ') { newstr[j] = '%'; newstr[++j] = '2'; newstr[++j] = '0'; } else { newstr[j] = str[i]; } }
Or, if you want to keep the reverse loop (no need to highlight another line with this):
for (i = length - 1, j = newLength - 1; i >= 0; i--, j--) { if(str[i] == ' ') { str[j] = '0'; str[--j] = '2'; str[--j] = '%'; } else { str[j] = str[i]; } }
krtek
source share