-
Notifications
You must be signed in to change notification settings - Fork 0
/
3lastword.c
49 lines (43 loc) · 976 Bytes
/
3lastword.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Write a program that takes a string and displays its last word followed by a \n.
// A word is a section of string delimited by spaces/tabs or by the start/end of
// the string.
// If the number of parameters is not 1, or there are no words, display a newline.
// Example:
// $> ./last_word "FOR PONY" | cat -e
// PONY$
// $> ./last_word "this ... is sparta, then again, maybe not" | cat -e
// not$
// $> ./last_word " " | cat -e
// $
// $> ./last_word "a" "b" | cat -e
// $
// $> ./last_word " lorem,ipsum " | cat -e
// lorem,ipsum$
// $>
#include <unistd.h>
void last_word(char *str)
{
int i = 0;
while (str[i] != '\0')
i++;
i -= 1;
while(str[i] == '\t' || str[i] == 32)
i--;
while (i > 0)
{ if(str[i] == 32 && str[i] == '\t')
break;
i--;
}
i++;
while (str[i] != '\0' && str[i] != 32 && str[i] != '\t')
{
write(1, &str[i], 1);
i++;
}
}
int main(int ac, char **av)
{
if (ac == 2)
last_word(av[1]);
write(1, "\n", 1);
}