String help

Im having some problems with a program to make nouns plural. It always works for the first case but I get undesirable results for each subsequent case. Here is what I have so far:

char * pluralize (char *str)
{
unsigned length;

length=strlen(str);

if (str[length-1]=='y') {
str[length-1]=0;
strcat(str, "ie");
}

if (str[length-1]=='s') {
strcat(str, "e");
}

if (str[length-2]=='c' && str[length-1]=='h') {
strcat(str, "e");
}

if (str[length-2]=='s' && str[length-1]=='h') {
strcat(str, "e");
}

strcat(str, "s");

return str;
}
int main (void)
{
printf("Plural is %s
", pluralize("chair"));
printf("Plural is %s
", pluralize("dairy"));
printf("Plural is %s
", pluralize("boss"));
printf("Plural is %s
", pluralize("circus"));
printf("Plural is %s
", pluralize("fly"));
printf("Plural is %s
", pluralize("dog"));
printf("Plural is %s
", pluralize("church"));
printf("Plural is %s
", pluralize("clue"));
printf("Plural is %s
", pluralize("dish"));

return 0;
}

The output is:

Plural is chairs
sssss

Any help would be great, thank you!

Comments

  • You need to provide additional memory to hold the endings.
    [code]
    char * pluralize (char *str)
    {
    unsigned length;

    length=strlen(str);

    [color=Red]char* str2 = malloc(length+3);
    strcpy(str2, str);[/color]

    if (str[length-1]=='y') {
    str[color=Red]2[/color][length-1]=0;
    strcat(str[color=Red]2[/color], "ie");
    }

    if (str[length-1]=='s') {
    strcat(str[color=Red]2[/color], "e");
    }

    if (str[length-2]=='c' && str[length-1]=='h') {
    strcat(str[color=Red]2[/color], "e");
    }

    if (str[length-2]=='s' && str[length-1]=='h') {
    strcat(str[color=Red]2[/color], "e");
    }

    strcat(str[color=Red]2[/color], "s");

    return str[color=Red]2[/color];
    }
    int main (void)
    {
    printf("Plural is %s
    ", pluralize("chair"));
    printf("Plural is %s
    ", pluralize("dairy"));
    printf("Plural is %s
    ", pluralize("boss"));
    printf("Plural is %s
    ", pluralize("circus"));
    printf("Plural is %s
    ", pluralize("fly"));
    printf("Plural is %s
    ", pluralize("dog"));
    printf("Plural is %s
    ", pluralize("church"));
    printf("Plural is %s
    ", pluralize("clue"));
    printf("Plural is %s
    ", pluralize("dish"));

    return 0;
    }
    [/code]
    You'd also want to either free() the returned memory later after calling pluralize or to have the main function provide the buffer to hold the pluralized string.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion