How to check if a given string exists in a matrix of characters with C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define COLS 5

bool string_exists_in_matrix_of_characters(char matrix[][COLS], char str[], int rows, int cols) {
    char matrix_str[64] = {0};

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix_str[i * cols + j] = matrix[i][j];
        }
    }

    return strstr(matrix_str, str);
}

int main() {
    char matrix[][COLS] = {
        	{'D', 'E', 'F', 'X', 'Y'},
	        {'A', 'O', 'E', 'P', 'Z'},
	        {'D', 'Q', 'C', 'O', 'D'},
	        {'E', 'B', 'E', 'D', 'S'},
	        {'C', 'P', 'Y', 'G', 'H'} };
	        
    char str[] = "CODE";

    int rows = sizeof(matrix) / sizeof(matrix[0]);
    int cols = sizeof(matrix[0]) / sizeof(matrix[0][0]);

    if (string_exists_in_matrix_of_characters(matrix, str, rows, cols)) {
        puts("Exist");
    } else {
        puts("Not exist");
    }

    return 0;
}



/*
run:

Exist

*/

 



answered Apr 15, 2024 by avibootz
edited Apr 15, 2024 by avibootz
...