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
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]withargc[3][0].You also don't need to swap characters between
argv[2]andargv[3]when you find a match.