This is my attempted solution to Question 1.3 from "Cracking the Code Interview", 6th ed.
Question:
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the true length of the string.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
// Input: "Mr John Smith ", 13
// Output: "Mr%20John%20Smith"
int countSpaces(char* str) {
int i = 0, j = 0;
while (str[i] != '\0')
if ( str[i++] == ' ')
j++;
return j;
}
char* replaceChars(char* str, int length) {
int x = countSpaces(str);
int stringLength = length + x - x/3;
char* urlifiedString = malloc((stringLength + 1) * sizeof(char));
int i = 0, j = 0;
while (i < stringLength) {
if (str[j] != ' ') {
urlifiedString[i++] = str[j];
} else if (str[j] == ' '){
urlifiedString[i++] = '%';
urlifiedString[i++] = '2';
urlifiedString[i++] = '0';
}
j++;
}
urlifiedString[stringLength] = '\0';
return urlifiedString;
}
int main() {
char* result1 = replaceChars("Mr John Smith ", 13);
printf("%s\n", result1);
printf("%li\n", strlen(result1));
assert(strcmp("Mr%20John%20Smith", result1) == 0);
free(result1);
char* result2 = replaceChars("lol lol lol ", 12);
printf("%s\n", result2);
assert(strcmp("lol%20%20lol%20lol", result2) == 0);
free(result2);
char* result3 = replaceChars("", 0);
assert(strcmp("", result3) == 0);
free(result3);
return 0;
}