A simple program to search and replace characters in a character array. Written in C language
//
// main.c
// This module displays how to search and replace a char
// in a char array by iteration through the char array
//
// Created by Rob Hunter on 10/24/18.
// Copyright © 2018 Rob Hunter. All rights reserved.
//
#include <stdio.h>
#include <string.h>
int change(char*, char, char);
int main () {
char x[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'x', 't', 'f', 'm', 'x', 't', 'y'};
char changeFrom = 'x';
char changeTo = '*';
int count;
/* change chars from changeFrom to changeTo in char array x */
count = change(x, changeFrom, changeTo);
printf("String had %d char \'%c\' that were changed to \'%c\'\n\n", count, changeFrom, changeTo);
return 1;
}
/* change char variable y in char array x to char z */
int change(char *x, char y, char z) {
int i, count = 0;
char *test = x;
/* compare characters to y, if test == y change to z */
while ((test = strchr(x, y))) {
count++;
*test = z;
test++;
}
/* print string x */
for(i = 0; i < strlen(x) - 1; i++) {
printf("%c ", x[i]);
}
/* new line */
printf("\n\n");
return count;
}