#include <stdio.h>
#include <string.h>
#include <stdlib.h>


char *strreplace(char * string, char * sub, char * replace);

int main(void){
    char * mystring = "Here is my string.";
	char * sub = " ";
	char * replace = "__++";

	char * newString = strreplace(mystring, sub, replace);
	printf("new string: %s\n", newString);
	return 0;
}

//my replace
char *strreplace(char *string, char *sub, char *replace)
{
	if(!string || !sub || !replace) return NULL; // we need all inputs

	char *result = (char*)malloc(1); // malloc memory for new string, will be realloc later
	if(result == NULL){
		printf("malloc returned null\n");
		return NULL;
	}
	
	char *pos = string; // set pointer of pos to start of string
	char *pos1; // pointer to search for sub
	while((pos1 = strstr(pos, sub))) // search for sub and point to start of memory location
	{ 
		int len = (pos1 - pos); // length = found memory locatino - beginning of string
		result = realloc(result, strlen(result) + len + strlen(replace) + 1); // realloc result for string + replacemenet string + \0

		strncat(result, pos, len); // pull up to this location
		strncat(result, replace, strlen(replace)); //replace the found (strcat is fine because we already allocated the memory)
		pos = (pos1 + strlen(sub)); // update pos to find next occurance of sub in string
	}

	// if we aren't at the end of the original string, we need to get what's left of original string
	if(pos != (string + strlen(string)))
	{
		result = realloc(result, strlen(result) + strlen(pos) + 1); // realloc for what is left of original string
		strcat(result, pos); // get the rest of the original string
	}
	
	return result; // return new string
}