search_replace.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. (void) *argv;
  28. int i;
  29. int no_ch;
  30. int j;
  31. no_ch = 0;
  32. i = 0;
  33. j = 0;
  34. if (argc == 4 && argv[2][1] == '\0' && argv[3][1] == '\0')
  35. {
  36. while (argv[1][i])
  37. {
  38. if (argv[1][i] != argv[2][0])
  39. {
  40. i++;
  41. no_ch++;
  42. }
  43. else
  44. {
  45. argv[1][i] = argv[3][0];
  46. i++;
  47. }
  48. }
  49. if (no_ch == i)
  50. write(1, "\n", 1);
  51. else
  52. while(i)
  53. {
  54. write(1, &argv[1][j], 1);
  55. j++;
  56. i--;
  57. }
  58. }
  59. else
  60. write(1, "\n", 1);
  61. return (0);
  62. }