It's much cleaner if you use toupper(). And switch() helps too I think:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void pluralize(char *str)
{
char *plural = NULL;
int len = strlen(str);
if(!*str)
return;
if(!(plural = malloc(len+3)))
{
puts("Memory allocation error");
return;
}
switch(toupper(str[len-1]))
{
case 'Y':
strncpy(plural, str, len-1);
strcpy(plural+(len-1), "ies");
break;
case 'S':
sprintf(plural, "%ses", str);
break;
case 'H':
if(len > 1 &&
(toupper(str[len-2]) == 'C' || toupper(str[len-2]) == 'S'))
{
sprintf(plural, "%ses", str);
break;
}
default: // fall through from case 'H' if ending is not ch/sh
sprintf(plural, "%ss", str);
}
puts(plural);
free(plural);
}
int main(int argc, char **argv)
{
int i;
if(argc < 2)
{
puts("Usage: plural <word>[ <word>[ ...]]");
exit(EXIT_FAILURE);
}
for(i = 1;i < argc;++i)
pluralize(argv[i]);
return 0;
}