Struziu Struziu - 1 month ago 8
C Question

Program that returns words that ends and starts with the same letter

I have problem with my alignement. This time I want my program to return words that ends and starts with the same letter. I've wrote something like this, but it seems to return random words.

#include <stdio.h>
#include <string.h>

void main()
{
char str[100];
int i, t, j, len;

printf("Enter a string : ");
scanf("%[^\n]s", str);

len = strlen(str);
str[len] = ' ';

for (t = 0, i = 0; i < strlen(str); i++)
{
if ((str[i] == ' ') && (str[i - 1] == str[0]))
{
for (j = t; j < i; j++)
printf("%c", str[j]);
t = i + 1;
printf("\n");
}
else
{
if (str[i] == ' ')
{
t = i + 1;
}
}
}
}

Answer

You can use strtok to split the strings from stdin, then apply a letter checker on each parsed word one at a time.

Something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAXCHAR 100

int is_start_end(char *word);
void exit_if_null(void *ptr, const char *msg);

int
main(void) {
    char str[MAXCHAR];
    char *word;
    char **all_words;
    int words_size = 1, word_count = 0;
    int i, found;

    all_words = malloc(words_size * sizeof(*all_words));
    exit_if_null(all_words, "initial Allocation");

    printf("Enter words(enter empty line to terminate):\n");
    while (fgets(str, MAXCHAR, stdin) != NULL && strlen(str) != 1) {
        word = strtok(str, " \n");

        while (word !=NULL) {
            if (words_size == word_count) {
                words_size *= 2;
                all_words = realloc(all_words, words_size * sizeof(*all_words));
                exit_if_null(all_words, "Reallocation");
            }
            all_words[word_count] = malloc(strlen(word)+1);
            exit_if_null(all_words[word_count], "Initial Allocation");

            strcpy(all_words[word_count], word);

            word_count++;

            word = strtok(NULL, " \n");
        }
    }

    printf("Words that have equal first and last letters:\n");

    found = 0;
    for (i = 0; i < word_count; i++) {
        if (is_start_end(all_words[i])) {
            found++;
            printf("%s\n", all_words[i]);
        }
        free(all_words[i]);
        all_words[i] = NULL;
    }

    if (found == 0) {
        printf("None Found\n");
    }

    free(all_words);
    all_words = NULL;

    return 0;
}

int
is_start_end(char *word) {
    int len;

    len = strlen(word);

    if ((len == 1) || (tolower(word[0]) == tolower(word[len-1]))) {
        return 1;
    }
    return 0;
}

void
exit_if_null(void *ptr, const char *msg) {
    if (!ptr) {
        printf("Unexpected null pointer: %s\n", msg);
        exit(EXIT_FAILURE);
    }
}
Comments