c - "Anagram"用C写的程序

标签 c anagram

完全披露我是一名正在做家庭作业的大学生。我不一定是在寻找我的问题的直接答案,而是在寻找正确方向的插入力。所以这是我的问题。我必须编写一个接受 2 个命令行参数的 C 程序,一个是包含单词列表的文件,另一个是单个单词。现在,我之所以将 anagram 这个词用引号括起来,是因为它真的不是一个 anagram。

以下是题目要求: 我需要从命令行 (dog) 中获取单词并将其与字典列表 (doggie) 进行比较。如果命令行单词中的字母存在,那么我需要输出这样的消息 You can't spell "doggie"without "dog"! 所以我只是检查命令行参数中的字母存在于字典文件中的单词中。

这是我目前所拥有的:

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

#define MAX_WORD_LENGTH 80

int anagram(char a[], char b[]);

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <list> <goal>\n", argv[0]);
        return -1;
    }
    FILE *file = fopen(argv[1], "r");

    if (file == 0) {
        fprintf(stderr, "%s: failed to open %s\n", argv[0], argv[1]);
    } else {
        char cmdLn[MAX_WORD_LENGTH], comp[MAX_WORD_LENGTH];
        strcpy(cmdLn, argv[2]);
        while (fgets(comp, sizeof comp, file) != NULL) {
            strtok(comp, "\n");
            int flag = anagram(cmdLn, comp);
            if (flag == 1) {
                printf("You can't spell \"%s\" without \"%s\".\n", cmdLn, comp);
            } else {
                printf("There's no \"%s\" in \"%s\".\n", cmdLn, comp);
            }
        }
        fclose(file);
    }
    return 0;
}

int anagram(char a[], char b[]) {

    return 1;
}

所以我需要想出一个算法来比较命令行单词的每个字符和字典文件中单词的每个字符。如果我从 anagram 函数中找到每个字母 I,我会返回 1,否则我会返回 0。我根本不知道如何解决这个问题。任何帮助将不胜感激。

编辑:为了澄清,我可以假设字典文件和命令行中的所有字母都是小写的。每个单词不能超过80个字符,单词中不能有数字。

最佳答案

典型的高级语言方法是使用字母的集合或哈希。但让我们保持简单:

Make a copy of the command line word.

Loop through the letters in the file word: Loop through the letters in the copy word: If a letter from each matches, strike out that letter in the copy word (e.g. change it to *)

After the loops, if all the letters of the copy word are gone (i.e. stars), it's a match

int anagram(char *a, char *b) {

    size_t counter = 0, a_len = strlen(a), b_len = strlen(b);

    char *c = strdup(a);

    for (int j = 0; j < b_len; j++) {
        for (int i = 0; i < a_len; i++) {
            if (c[i] == b[j]) {
                c[i] = '*';
                counter++;
                break;
            }
        }
    }

    free(c);

    return (counter == a_len);
}

您需要修复上述问题以忽略大小写。

关于c - "Anagram"用C写的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36580598/

相关文章:

c - sscanf 读取字符串但 %n 返回 0

c - 将两个不同的整数相加

python - defaultdict(list) 将所有值连接到一个列表中

java - 谁能解释一下这段代码是如何工作的?

python - 通过 Python 查找和分组字谜

java - 如何将给定字符串数组中的不同字谜组合在一起?

header 可以在没有文件的情况下存在吗?

c++ - 从 C 移植到 C++ 时应该注意什么

c - 列表 vector 打印不起作用

java - 字谜算法错误