Gio Ftop Gio Ftop - 2 months ago 8
C Question

replace a character element of an array for another character entered by user input

I have an array full of * characters. I need to replace any character from the array for another character that the user enters. Is it possible? I'll appreciate any suggestions. Thanks

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

strreplace(char[],char,char);
int main()
{
char s[17]="* * * *\n* * * * ";
char chr,repl_chr;
printf("%s", s);
printf("\nEnter character to be replaced: ");
chr=getchar();
fflush(stdin);
printf("\nEnter replacement character: ");
repl_chr=getchar();
printf("\nModified string after replacement is: \n");
strreplace(s,chr,repl_chr);
getch();
return 0;
}



strreplace(char s[], char chr, char repl_chr)
{
int i=0;
while(s[i]!=' ')
{
if(s[i]==chr)
{
s[i]=repl_chr;
}
i++;
}
puts(s);
return 0;
}

Answer

Change your strreplace so that the parameter chr gets converted into an index.

int strreplace(char s[], char chr, char repl_chr)
{
    int i = 0;

    // Convert the input char into an index.
    // Note that 1 is subtracted to make the index zero-based.
    // Remember that the user entered a one-based index.
    int index = chr - '0' - 1;
    if ((index < 0) || (index >= 8))
    {
        // Out of bounds.
        return -1;
    }
    while (s[i] != '\0')
    {
        if ((i/2) == index)
        {
            s[i] = repl_chr;
        }

        // Note: since every second char is to get ignored,
        // the increment must actually be 2 here.
        i += 2;
    }
    puts(s);
    return 0;
}