Search and replace programme with c doesn't work fine?

61 Views Asked by At

hey everyone i have a problem to solve with c but the programme doesnt work fine this is the subject :

Write a program called search_and_replace that takes 3 arguments, the first arguments is a string in which to replace a letter (2nd argument) by another one (3rd argument). If the number of arguments is not 3, just display a newline. If the second argument is not contained in the first one (the string) then the program simply rewrites the string followed by a newline.

Examples:

$>./search_and_replace "Papache est un sabre" "a" "o"
Popoche est un sobre

and this the full code ;

#include <unistd.h>

int main(int argc, char **argv)
{
    int i;
    int j;
    int k;   
    int replace;

    i = 0;
    j = 0;
    if (argc == 4)
    {
        while(argv[1][i])
        {
            while(argv[2][j] != '\0' && argv[1][i] == argv[2][j])
            {
                while(argv[3][k])
                {
                    k = 0;
                    replace = argv[2][j];
                    argv[2][j] = argv[3][k];
                    argv[3][k] = replace;
                    k++;
                }
                argv[1][i] = argv[2][j];
                j++;
            }
            write(1, &argv[1][i], 1);
            i++;
        }
    }
}

i'm trying to change variables declaration inside the loops and also make all condition in juste 2 while

1

There are 1 best solutions below

0
Barmar On

You have several unnecessary loops. The 2nd and 3rd arguments are just single characters, not strings that you need to loop over. You just replace any occurrences of argc[2][0] with argc[3][0].

You also don't need to swap characters between argv[2] and argv[3] when you find a match.

#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc == 4 && strlen(argc[2]) > 0 && strlen(argc[3]) > 0)
    {
        char *string = argc[1];
        char old = argc[2][0];
        char new = argc[3][0];

        for (int i = 0; string[i]; i++) {
            if (string[i] == old) {
                string[i] = new;
            }
        }
        write(STDOUT_FILENO, string, strlen(string));
    }
    write(STDOUT_FILENO, "\n", 1); // write a newline after the replacement
}