I have to request a first word to compare it to a second word, and replace all occurrences with '*' working character by character without using the <string.h> library.
Exercise: Write a C program that receives two words entered from the keyboard as input. Consider that each word can contain a maximum of 30 characters. The program must be case sensitive, ie it must distinguish lowercase letters from uppercase letters and must also be able to analyze numbers, symbols and punctuation marks. The program must replace each occurrence of the second word in the first word with the '*' character. For example, enter the words
abchdfffchdchdtlchd
and
chd
the program should display the word
ab*fff**tl*
#include <stdio.h>
#include <stdlib.h>
#define MAX 30
int main()
{
char string1 [MAX+1], string2 [MAX+1],replace = '*';
int nChar1 = 0, nChar2 = 0, flag = 0, h=0;
printf ("Enter a word (max 30 characters): ");
scanf ("%[^\n ]", &string1);
fflush (stdin);
printf ("\nYou wrote this word: %s\n", string1);
for (int i=0; i<(MAX+1); i++)
{
if (string1[i] == '\0')
break;
else
nChar1++;
}
printf ("The characters are: %d\n", nChar1);
printf ("\nEnter a word you want to change with '*' in the first string: ");
scanf ("%[^\n ]", &string2);
fflush (stdin);
printf ("\nYou wrote this word: %s\n", string2);
for (int j=0; j<(MAX+1); j++)
{
if (string2[j] == '\0')
break;
else
nChar2++;
}
printf ("The characters are: %d\n", nChar2);
for (int i=0, j=0, z=0; i<nChar1, j<nChar2; i++, j++)
{
if (string1[i] == string2[j])
{
for (int k=0; k<nChar2; k++)
{
if (string1[i+k] == string2[j+k])
flag++;
else
flag=0;
}
}
j=0;
if (flag == nChar2)
{
string1[h] = replace;
h++;
}
else
{
h++;
}
string1[z+1] = string1[h];
}
printf("\n%s", string1);
return 0;
}