TheAlgorithms-C/exercism/acronym/acronym.c

92 lines
1.7 KiB
C
Raw Normal View History

2018-01-25 00:24:43 +03:00
#include <ctype.h>
#include <stdio.h>
#include <string.h>
2018-01-25 00:24:43 +03:00
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.
2018-01-25 00:24:43 +03:00
for determine the number of words
*/
while (p_str && (i < 80))
{
if (*p_str == ' ')
{
counter++;
}
if (i < 80)
{
p_str++;
i++;
}
}
i = 0;
counter++;
2020-06-07 00:09:51 +03:00
char **words = (char **)malloc(counter * sizeof(char *));
2018-01-25 00:24:43 +03:00
/* initalizes words-array with empty strings */
for (i = 0; i < counter; i++)
{
2020-06-07 00:09:51 +03:00
words[i] = (char *)malloc(80 * sizeof(char));
strcpy(words[i], "");
2018-01-25 00:24:43 +03:00
}
/* 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]);
2020-06-07 00:09:51 +03:00
free(words);
2018-01-25 00:24:43 +03:00
return acr;
2020-06-07 00:09:51 +03:00
}