/* 
 * Program with function to replace one character with another in a string.
 */
#include <stdio.h>
#include <string.h>

/* replace "oldchar" with "newchar" in "s" and return number of replacements */
int replace_in_string(char s[], char oldchar, char newchar) {

	int count = 0;
	
	for (int index = 0; s[index] != '\0' ; index +=1) {
		if (s[index] == oldchar) {
			s[index] = newchar;
			count += 1;
		}
	}
	return count;
}

/* another way to write the same thing */
int replace_in_string2(char* s, char oldchar, char newchar) {

	int count = 0;

	for (char* p = s; *p != '\0' ; p += 1) {
		if (*p == oldchar) {
			*p = newchar;
			count += 1;
		}
	}
	return count;
}

/* main */
int main(void) {

	char input[20];
	int result;

	strcpy(input, "hello");
	printf("initial value %s\n", input);
	result = replace_in_string(input, 'l', 'L');
	printf("result of replacing 'l' with 'L' %s (%d replacements)\n", 
            input, result);
	result = replace_in_string(input, 'z', 'Z');
	printf("result of replacing 'z' with 'Z' %s (%d replacements)\n", 
            input, result);

	return 0;	
}