检查两个字符数组是否相等C.

时间:2014-01-31 01:43:19

标签: c arrays

我正在尝试编写一个程序来检查输入到程序的单词是否与预定义的关键字匹配。输入将来自文本文件,文本文件中将包含一个单词。到目前为止,文本文件我只有“青蛙”这个词,这意味着该程序应该清楚地打印“找不到匹配”,但它实际上打印出“匹配找到”它打印出“匹配找到”即使文本文件中的单词也是如此是一串随机字母。这是我的代码,你们有什么突出的吗?感谢

#define NUM 4
#define SIZE 12

int isAlpha(char);

//Returns 1 if it is an Alphabetical character, 0 if it is not
int isAlpha(char c) {
  return (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z');
}

int main() {
  char message[141];
  int charCount = 0, c = 0, matchCheck = 0;

  char keywords[NUM][SIZE] = {
    "crackerjack",
    "Hey",
    "dog",
    "feet"
  };

  //Removes non alphabetical characters
  while((c = getchar()) != EOF && charCount <= 140) {
    if(isAlpha(c)){
      message[charCount] = c;
      charCount++;
    }
  }

  //checks if message matches keyword
  for (int i = 0; i < NUM; i++) {
    for (int j = 0; j < SIZE; j++) {

      //Check if current two characters match
      if (message[j] == keywords[i][j]) {
        //Check if the two matched characters are the null terminator character
      if (message[j] == '\0' && keywords[i][j] == '\0') {
          matchCheck = 1;
          break;
      }
    }  
  } 
}


  //prints "Match Found!" if there was a match
  if (matchCheck == 1)
    printf("Match Found!\n");
  else 
    printf("No Match Found\n");

}

1 个答案:

答案 0 :(得分:0)

我很长一段时间没用C编程,现在我也没有C编译器。但是,我认为逻辑可能存在问题。您需要单独检查每个单词。我会为你的上一节做以下几点......

matchAnyWord = 0

for (int i = 0; i < NUM; i++) {
    matchCheck = 1; 

    for (int j = 0; j < SIZE; j++) {
        if (message[j] == '\0' && keywords[i][j] == '\0') break;
        if (message[j] == '\0' && keywords[i][j] != '\0') { matchCheck = 0; break;}
        if (message[j] != '\0' && keywords[i][j] == '\0') { matchCheck = 0; break;}
        if (message[j] != keywords[i][j] ) { matchCheck = 0; break;}
    } 

    if (matchCheck == 1) {matchAnyWord = 1; break;}
}

请注意,我们在这里检查单个单词的匹配,并引入一个新的变量matchAnyWord,这实际上就是你想要的。我可能在语法上有错误,但我认为逻辑应该或多或少。

干杯!

另外,不确定为什么缩进在我的浏览器上没有正确显示...