简体   繁体   English

使用strcmp搜索相等的字符串

[英]Searching for equal strings using strcmp

I have a 2D array containing real words of the same length (dictionary). 我有一个2D数组,其中包含相同长度的实词(字典)。 I also have a 2D array of strings (mostly rubbish, with some real words in there). 我也有一个二维的字符串数组(主要是垃圾,里面有一些真实的单词)。 I'm trying to find the real words in the second array by using strcmp. 我正在尝试使用strcmp在第二个数组中找到真实的单词。 Once a real word is found (strcmp = 0), I want to copy that word into a new 2D string array called actual_words then print it. 一旦找到一个真实单词(strcmp = 0),我想将该单词复制到一个新的2D字符串数组中,该数组称为actual_words然后进行打印。

However mine seems to just print Words which are viable: and no actual words ... no errors though. 但是我的似乎只是打印Words which are viable:没有实际单词……虽然没有错误。

All strings are null terminated. 所有字符串均以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");
}

You are using the same index in the comparison for both arrays: 您在两个数组的比较中使用相同的索引:

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

Array equal_length_dictionary should use index dict not arr . 数组equal_length_dictionary应该使用索引dict而不是arr

My guess it the comparison; 我猜是比较;

strcmp(equal_length_dictionary[arr], nextword[arr])

You use the same variable arr for both arrays. 您对两个数组都使用相同的变量arr The first array should be indexed by dict I would guess: 第一个数组应该由我猜的dict索引:

strcmp(equal_length_dictionary[dict], nextword[arr])

Also, both strings needs to be zero-terminated or you would have undefined behavior . 另外,两个字符串都必须以零结尾,否则您将有undefined behavior If the strings are not zero-terminated you need to use strncmp instead (or possibly memcmp ). 如果字符串不是以零结尾的,则需要使用strncmp代替(或者可能使用memcmp )。

Without seeing the words being compared I have one guess: 1. There are leading or trailing spaces you don't know about. 没有看到比较的单词,我有一个猜测:1.有些前导或尾随空格您不知道。 Try printing out the strings with delimiters in the print statement so you can easily see if there are any spaces that need to be trimmed. 尝试在打印语句中用定界符打印出字符串,以便您可以轻松查看是否需要修剪任何空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM