c - 使用 strcmp 搜索相等的字符串

标签 c arrays string strcmp

我有一个包含相同长度的真实单词(字典)的二维数组。我还有一个二维字符串数组(大部分是垃圾,其中有一些真实的单词)。我试图使用 strcmp 找到第二个数组中的真实单词。找到真实单词 (strcmp = 0) 后,我想将该单词复制到名为 actual_words 的新二维字符串数组中,然后打印它。

然而,我的似乎只是打印了Words that are Viable:,而没有实际的单词......不过没有错误。

所有字符串均以 null 结尾。

void check_dictionary (char equal_length_dictionary[MAX_WORDS][MAX_WORD_LENGTH], char nextword[MAX_WORDS][MAX_WORD_LENGTH])

{
int arr, dict;
char actual_words[MAX_WORDS][MAX_WORD_LENGTH];

printf("\nWords which are viable: \n");

for (dict = 0; equal_length_dictionary[dict][0] != '\0'; dict++)
{
//look through each word in dictionary
    for (arr = 0; nextword[arr][0] != '\0'; arr++) 
    //look through each word in the array
        {
                if ((strcmp(equal_length_dictionary[arr], nextword[arr])) == 0) 
                //test for differences between dictionary and word
                    {
                        strcpy(actual_words[arr], nextword[arr]); 
                        //if no differences, copy words
                        printf("%s ", actual_words[arr]);
                    }
        }
}     
printf("\n");
}

最佳答案

您在两个数组的比较中使用相同的索引:

if ((strcmp(equal_length_dictionary[arr], nextword[arr])) == 0) 

数组 equal_length_dictionary 应使用索引 dict 而不是 arr

关于c - 使用 strcmp 搜索相等的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653552/

相关文章:

C函数创建动态结构数组

java - 在java中对超大字符串数组进行排序

arrays - 在 Delphi 中定义记录 - (记录为类型与记录为变量)- 差异、缺点和优点..?

arrays - 从数组状态ReactJS中删除一个对象

linux - 如何在 linux 中使用就地编辑 sed 将包含字符串的行上的特定记录替换为另一个文件中的数字

mysql - 如何在不使用 ENUM 的情况下强制执行 MySQL 表中的某些字符串?

c - 如何使用整数的小数

c - 如何在c中通过匿名管道发送消息

比较人物

c# - 在 C# 中,大写和小写字符串/字符串有什么区别?