Replace all spaces in c-style string with '%20'

Problem Write a C program that will replace all spaces with ‘%20′ Examples Input: s = "Mr John Smith" Output: "Mr%20John%20Smith Solution Method 1 - Count spaces and traverse from end The algorithm is as follows: Count the number of spaces during the first scan of the string. Parse the string again from the end and for each character: If a space is encountered, store “%20”. Else, store the character as it is in the newly shifted location. Code C void replaceSpaces(char[] str, int length) { int spaceCount = 0, newLength, i = 0; for (i = 0; i < length; i++) { if (str[i] == ' ') { spaceCount++; } } newLength = length + spaceCount * 2; str[newLength] = '\0'; 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; } } } ...

This site uses cookies to improve your experience on our website. By using and continuing to navigate this website, you accept this. Privacy Policy