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

1 Answer

0 votes
#include <iostream>

#define COLS 5
 
bool string_exists_in_matrix_of_characters(char matrix[][COLS], std::string str, int rows, int cols) {
    std::string matrix_str;
 
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix_str += matrix[i][j];
        }
    }
    return matrix_str.find(str) != std::string::npos;
}
 
int main() {
    char matrix[][COLS] = {
            {'D', 'E', 'F', 'X', 'Y'},
            {'A', 'O', 'E', 'P', 'U'},
            {'D', 'D', 'C', 'O', 'D'},
            {'E', 'B', 'E', 'D', 'S'},
            {'C', 'P', 'Y', 'G', 'N'} };
             
    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)) {
        std::cout << "Exist";
    } else {
        std::cout << "Not exist";
    }
}
 
 
 
/*
run:
 
Exist
 
*/

 



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