2014-01-31 45 views
0

可以说我有一个二维数组包含3个不同的单词列表。我正在尝试检查预定义的单词是否与列表中的任何单词相同。 strcmp函数的格式是什么?Strcmp为二维数组

实施例:

char message[5] = {"hello"}; 

char keywords[3][10] = {"dolphin", 
         "rhino", 
         "hello" }; 

for(int i = 0; i < 3; i++) { 
    for(int j = 0; j < 5; j++) { 
    if(strcmp(message, keywords[i][0]) == 0) { 
     printf("Match Found!"); 
     break; 
    } 
    else 
     break; 
    } 
} 

回答

2

更改strcmp

strcmp(message, keywords[i]) 

字符串比较功能需求两个字符串。 keywords[i][0]是字符串的第一个字符。所以你正在比较字符串和字符。

用来给予警告如

/usr/include/string.h:143:12

gcc编译:注意:预期 '为const char *',但参数的类型为 '字符'

代码:

#include <sys/time.h> 
#include <sys/resource.h> 
#include <stdio.h> 
#include <string.h> 

int main(){ 
char message[5] = {"hello"}; 
char keywords[3][10] = {"dolphin", 
         "rhino", 
         "hello" }; 

for(int i = 0; i < 3; i++) { 
    for(int j = 0; j < 5; j++) { 
     printf("Check 1 : %c\n", keywords[i][0]); 
     printf("check 2 : %s\n", keywords[i]); 
     //printf("%s\n", keywords[i][0]);// try this you will get error 
     if(strcmp(message, keywords[i]) == 0) { 
      printf("Match Found!\n"); 
      break; 
     } 
     else 
      break; 
    } 
} 

return 0; 
} 

输出:

Check 1 : d 
check 2 : dolphin 
Check 1 : r 
check 2 : rhino 
Check 1 : h 
check 2 : hello 
Match Found! 
+0

非常好的解释... –

1

keywords[3][10]装置,每个最大长度103字符串数组。

因此,您正在访问的字符串错误的方式:

当你写keyword[i][0]这意味着i个字符串的0个字符。
但是,你所需要的仅仅是i个字符串,则需要取消引用它第二次,也就是说,你应该使用:

if(strcmp(message, keywords[i]) == 0)

0

这样就可以比较两个字符串。

#include<stdio.h> 
#include<string.h> 
#include<conio.h> 
    int main(){ 
    char message[6] = {"rhino"}; 
    char keywords[3][10] = {"dolphin", 
          "rhino", 
          "hello" }; 

     for(int i = 0; i < 3; i++) { 
      for(int j = 0; j < 5; j++) { 

       if(strcmp(message, keywords[i]) == 0) { 
         printf("Match Found!"); 
       printf("\n %s Match with %s",message, keywords[i]); 
         break; 
       } 
       else 
       break; 
     } 
     } 
    getch(); 
    return 0; 
} 

让我知道,如果有什么问题!!!

0

改变你的strcmp功能

for(i=0;i<=5;i++) 
     { 
      if(strcmp(&keybord[i][0],message)) 
     } 

,并享受:)