如何检查二维数组中一行中的每个元素在 C 中是否相同?

问题描述

因此,例如,如果我有一个 2D 字符数组座位Chart[5][5] =

x x . x x
. x . x x
. . . . .
x x x x .
. . . . .

如何打印出第 3 行和第 5 行都是“.”?

我正在尝试这样做

for (int row = 0; row < 5; row++) {
                for (int col = 0; col < 5; coL++) {
                    }
                if (seatingChart[row][0-9] == "."){
                        printf("Row %d is empty",row+1);
                }
            }
        }

是否有更快的方法来做到这一点,而无需在 if 语句中多次写入 && ?因为我的实际座位表有 1000 行和 1000 列

解决方法

你可以这样做

  1. 设置“此行中的所有元素均为 .”标志。
  2. 遍历行。
  3. 当您找到不是 . 的元素时,清除标记。
  4. 迭代后,检查标志以查看结果。
#include <stdio.h>

int main(void) {
    char seatingChart[5][5] = {
        "xx.xx",".x.xx",".....","xxxx.","....."
    };

    for (int row = 0; row < 5; row++) {
        int is_all_dot = 1;
        for (int col = 0; col < 5; col++) {
            if (seatingChart[row][col] != '.') {
                is_all_dot = 0;
                break;
            }
        }
        if (is_all_dot) {
            printf("Row %d is empty\n",row + 1);
        }
    }

    return 0;
}
,

您只需检查下一个元素是否与当前元素相同,如果整行都通过了,那么您将行索引标记为完全相同。如果任何检查失败,您可以移至下一行,因为它会使整行无效。

,

为此,我建议编写一个单独的函数来检查行。这既使程序更具可读性,并且您可以使用提前返回作为算法的一部分:

bool row_empty(size_t row_length,const char row[row_length])
{
  for (size_t n = 0; n < row_length; n++)
    { 
      /*
        As soon as we see a non-empty seat,we know that the
        row is empty
       */
      if (row[n] != '.')
        return false;
    }

  /* We only reach this point if all the seats were empty */
  return true;
}

现在,遍历您的行变得非常简单:

for (int row = 0; row < num_rows; row++)
  {
    if (row_empty(row_length,seatingChart[row])
      {
         printf("Row %d is empty",row+1);
      }
  }

一些最后的笔记:

为了您的利益,我删除了硬编码值 5。 您必须添加 #include <stdbool.h> 才能使用 booltruefalse。 如果您的编译器没有 stdbool.h,则必须使用 int10