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

标签 c arrays char

我正在尝试编写一个程序来检查输入到程序中的单词是否与预定义关键字之一匹配。输入将来自一个文本文件,文本文件中只有一个单词。到目前为止,我的文本文件只有“crackerjack”这个词,这意味着程序应该清楚地打印“找到匹配项”,但它目前没有这样做。这是我的代码,你们有什么突出的地方吗?谢谢

#define NUM 4
#define SIZE 11

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",
    "fish"
  };

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

  //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;
      } 
      //if characters are not the same, break from loop
      else {
        break;
      }  
    } 
  }


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

最佳答案

您的代码中存在 3 个问题。其中两个已经得到解决:

  1. 确保 SIZE 足够大,可以在最长关键字的末尾包含一个 '\0'

  2. 确保文本文件在单词末尾包含 '\0'。如果不是这种情况或超出您的控制范围,您始终可以在读取字符串后手动以 '\0' 结尾。

  3. 您在第二个 if 语句中缺少括号。这会导致每次输入第一个 if 语句时执行 break 语句。

关于在 C 中检查两个字符数组是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21441704/

相关文章:

c++ - 如何在 VS2008 中指定 64 位 unsigned int const 0x8000000000000000?

arrays - 如何确定 C 中数组的大小?

arrays - C程序去除字符串中连续重复的字符

c++ - 将 std::string 转换为 char *

c - 将字符数组转换为字符串数组的问题

c - linux 中 pthread_create 中的 'arg'

c - 两个 fork 进程之间的消息队列导致来自 msgsnd 的参数无效

用递归函数计算数组的平均值

C char**,字符串数组空指针

Java:扩展数组大小,似乎无法将所有值保留在原始位置