-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathacronym.c
91 lines (76 loc) · 1.71 KB
/
acronym.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *abbreviate(const char *phrase)
{
char str[80];
strcpy(str, phrase);
char *p_str = str;
static char acr[80];
strcpy(acr, "");
/* for counting the words */
int counter = 0;
/* for position the words */
int index = 0;
/* for -loop variable */
int i = 0;
/*
counts the empty-characters.
for determine the number of words
*/
while (p_str && (i < 80))
{
if (*p_str == ' ')
{
counter++;
}
if (i < 80)
{
p_str++;
i++;
}
}
i = 0;
counter++;
char **words = (char **)malloc(counter * sizeof(char *));
/* initalizes words-array with empty strings */
for (i = 0; i < counter; i++)
{
words[i] = (char *)malloc(80 * sizeof(char));
strcpy(words[i], "");
}
/* rewind string */
p_str = str;
char *p_start = p_str;
/* collects each word in array 'words' */
while (p_str && (i <= 80))
{
if (*p_str == ' ')
{
*p_str = '\0';
strncat(words[index], p_start, 80);
index++;
p_start = p_str + 1;
}
if (i <= 80)
{
p_str++;
i++;
}
}
/* adds the last word */
*p_str = '\0';
strncat(words[index], p_start, 80);
index++;
/* builds the actual acronym */
for (i = 0; i < index; i++)
{
/* capitalize the first character */
words[i][0] = toupper(words[i][0]);
words[i][1] = '\0';
strcat(acr, words[i]);
}
for (i = 0; i < counter; i++) free(words[i]);
free(words);
return acr;
}