first_word.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Assignment name : first_word
  2. Expected files : first_word.c
  3. Allowed functions: write
  4. --------------------------------------------------------------------------------
  5. Write a program that takes a string and displays its first word, followed by a
  6. newline.
  7. A word is a section of string delimited by spaces/tabs or by the start/end of
  8. the string.
  9. If the number of parameters is not 1, or if there are no words, simply display
  10. a newline.
  11. Examples:
  12. $> ./first_word "FOR PONY" | cat -e
  13. FOR$
  14. $> ./first_word "this ... is sparta, then again, maybe not" | cat -e
  15. this$
  16. $> ./first_word " " | cat -e
  17. $
  18. $> ./first_word "a" "b" | cat -e
  19. $
  20. $> ./first_word " lorem,ipsum " | cat -e
  21. lorem,ipsum$
  22. $> */
  23. #include <unistd.h>
  24. int main(int argc, char **argv)
  25. {
  26. int i;
  27. i = 0;
  28. if (argc != 2)
  29. {
  30. write(1, "\n", 1);
  31. }
  32. else
  33. {
  34. while (argv[1][i])
  35. {
  36. if (argv[1][i] >= 0 && argv[1][i] <= 32)
  37. i++;
  38. else
  39. {
  40. write(1, &argv[1][i], 1);
  41. i++;
  42. if (argv[1][i] >= 0 && argv[1][i] <= 32)
  43. {
  44. write (1, "\n", 1);
  45. return (0);
  46. }
  47. }
  48. }
  49. }
  50. return (0);
  51. }