Convert a String into a square matrix grid of characters in C++


In this tutorial, we will be discussing a program to convert a string into a square matrix grid of characters.

For this we will be provided with a string of characters. Our task is to print that particular string in the format of a matrix grid having a certain number of rows and columns.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//converting the string in grid format
void convert_grid(string str){
   int l = str.length();
   int k = 0, row, column;
   row = floor(sqrt(l));
   column = ceil(sqrt(l));
   if (row * column < l)
      row = column;
   char s[row][column];
   for (int i = 0; i < row; i++) {
      for (int j = 0; j < column; j++) {
         s[i][j] = str[k];
         k++;
      }
   }
   //printing the new grid
   for (int i = 0; i < row; i++) {
      for (int j = 0; j < column; j++) {
         if (s[i][j] == '\0')
            break;
         cout << s[i][j];
      }
      cout << endl;
   }
}
int main(){
   string str = "TUTORIALSPOINT";
   convert_grid(str);
   return 0;
}

Output

TUTO
RIAL
SPOI
NT

Updated on: 06-Jan-2020

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements