c - 尝试比较二维数组中的字符串

标签 c arrays string strcmp

所以我创建了一个包含一堆单词的文件,我的程序应该打开该文件,将所有单词放入一个数组中,然后比较字符串以查看是否有完全匹配的字符串。它打开文件并填充数组,但是当我尝试比较字符串时,问题就出现了。任何人都可以告诉我如何解决为什么这不能正确比较的问题吗?

我的文字文件:

Google Twitter Facebook Twitter gmail Flyer city 
phone Google cookie Facebook Flyer grill fork silver tornado dirty 
blue grill lemon

代码:

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

int main(void) 
{ 
    FILE *words; 
    char words_array[20][17];
    int x=0; 
    int y=0;
    int pairs = 0;
    words=fopen("words.dat","r"); 
    if(words==NULL) 
        printf("\n\nwords.dat was not properly opened.\n");
      else
        {
                 for(x = 0 ; x < 20 ; x++ ) 
                 { 
            fscanf(words,"%s",&words_array[x][y]); 
                 } 
                 fclose(words); 
                         for(x = 0 ; x < 20 ; x++ )
                       printf("Word #%d is %s \n", x + 1, words_array[x]); 

            /*start of comparison*/

                for(x=0;x<20;x++)
                        {
              for(y=0;y<20;y++)
                           {
            if (strcmp (words_array[x], words_array[x+1])==0)
                pairs++;
                       }
                /*end of comparisons*/
                         }
                printf("%d \n",pairs);


        }
    return(0); 
} 

输出:

Word #1 is Google 
Word #2 is Twitter 
Word #3 is Facebook 
Word #4 is Twitter 
Word #5 is gmail 
Word #6 is Flyer 
Word #7 is city 
Word #8 is phone 
Word #9 is Google 
Word #10 is cookie 
Word #11 is Facebook 
Word #12 is Flyer 
Word #13 is grill 
Word #14 is fork 
Word #15 is silver 
Word #16 is tornado 
Word #17 is dirty 
Word #18 is blue 
Word #19 is grill 
Word #20 is lemon 
0 

最佳答案

您仅将当前行与下一行进行比较。将 strcmp 的循环更改为:

for(x=0; x<20; x++) {
    for(y=x+1; y<20; y++) {
        if (strcmp (words_array[x], words_array[y])==0)
            pairs++;
    }   
}

这将在您的示例数据中找到五对:

 Google
 Twitter
 Facebook
 Flyer
 grill

顺便说一句,您可能希望在程序开头(#includes 和 main 之间)添加一个已定义的行数常量,这样您就不必替换 20如果你想改变读取的行数(当然也可以改变字长):

#define MAXLINES 20
#define MAXLENGTH 17

然后您就可以在现在有 20 和 17 的任何地方使用这些常量。

关于c - 尝试比较二维数组中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915305/

相关文章:

c++ - 修改时是否复制 C++ 中的字符串?

c - 让 gcc 内联并导出函数

objective-c - #define 是本地的(在 xcode 中)吗?

c - 使用 FFmpeg libavformat 录制 RTSP 流

Python - 打印矩阵 w/o pprint

javascript - 比较两个数组并返回重复值

c - 如何在C中修改一个字符串中的内容?

java - 科学记数法作为 Double java Android

c - 编译 PortAudio 示例时出错

java - java中如何在字符列表中添加值并在下一个值为空时停止添加