返回以相同字母结尾并以相同字母开头的单词的程序

时间:2016-10-31 08:50:19

标签: c

我的对齐有问题。这次我希望我的程序返回以相同字母结尾的单词。我写过这样的东西,但它似乎回复了随机词。

#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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

此行删除字符串的空终止符:

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

因此字符串不再存在,剩下的只是一个普通的字符数组。

在for循环体中对strlen的下一次调用将导致未定义的行为。

答案 1 :(得分:1)

您可以使用strtokstdin拆分字符串,然后在每个解析的字词上一次应用一个字母检查器。

这样的事情:

#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 = 1;
            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);
    }
}
相关问题