This is a question from a CS diploma question set :
Make a program that will create an abbreviation of any given name using the initials. For example if the name if "John Doe", the program will output "J.D".
My Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *abbr (const char *s) {
int keywords = 1;
for (int i = 0; s[i]; i++)
if (s[i] == ' ') keywords++;
char *ret = (char *)malloc(2*keywords);
if (!ret) {
perror("malloc");
exit (EXIT_FAILURE);
}
char *str = strdup(s);
int i = 0;
for (char *tok=strtok(str, " "); tok; tok=strtok(NULL, " "))
{
ret [i++] = *tok;
ret [i++] = '.';
}
ret [--i] = 0;
free(str);
return ret;
}
int main (void) {
char name[] = "John Doe";
char *s = abbr(name);
puts (s);
free(s);
return 0;
}
With respect to the question, is this a good enough solution? Is there a better way to achieve the same thing?
Thank you.
.
required for that example input, that we'd normally write in English asJ.D.
? \$\endgroup\$