search_replace1.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* Assignment name : search_and_replace
  2. Expected files : search_and_replace.c
  3. Allowed functions: write, exit
  4. --------------------------------------------------------------------------------
  5. Write a program called search_and_replace that takes 3 arguments, the first
  6. arguments is a string in which to replace a letter (2nd argument) by
  7. another one (3rd argument).
  8. If the number of arguments is not 3, just display a newline.
  9. If the second argument is not contained in the first one (the string)
  10. then the program simply rewrites the string followed by a newline.
  11. Examples:
  12. $>./search_and_replace "Papache est un sabre" "a" "o"
  13. Popoche est un sobre
  14. $>./search_and_replace "zaz" "art" "zul" | cat -e
  15. $
  16. $>./search_and_replace "zaz" "r" "u" | cat -e
  17. zaz$
  18. $>./search_and_replace "jacob" "a" "b" "c" "e" | cat -e
  19. $
  20. $>./search_and_replace "ZoZ eT Dovid oiME le METol." "o" "a" | cat -e
  21. ZaZ eT David aiME le METal.$
  22. $>./search_and_replace "wNcOre Un ExEmPle Pas Facilw a Ecrirw " "w" "e" | cat -e
  23. eNcOre Un ExEmPle Pas Facile a Ecrire $ */
  24. #include <unistd.h>
  25. int main(int argc, char **argv)
  26. {
  27. int i;
  28. i = 0;
  29. if (argc == 4 && argv[2][1] == '\0' && argv[3][1] == '\0')
  30. while (argv[1][i])
  31. {
  32. if (argv[1][i] == argv[2][0])
  33. {
  34. argv[1][i] = argv[3][0];
  35. }
  36. else
  37. {
  38. argv[1][i] = argv[1][i];
  39. }
  40. write(1, &argv[1][i], 1);
  41. i++;
  42. }
  43. else
  44. write(1, "\n", 1);
  45. return (0);
  46. }